π OpenHands: AI-Driven Development
Removed the V0 resolver (#14062)
Tim O'Farrellcc100c0d10fb
diff --git a/.github/workflows/openhands-resolver.yml b/.github/workflows/openhands-resolver.ymldeleted file mode 100644index b905e1a2b6..0000000000--- a/.github/workflows/openhands-resolver.yml+++ /dev/null@@ -1,433 +0,0 @@-name: Auto-Fix Tagged Issue with OpenHands--on:- workflow_call:- inputs:- max_iterations:- required: false- type: number- default: 50- macro:- required: false- type: string- default: "@openhands-agent"- target_branch:- required: false- type: string- default: "main"- description: "Target branch to pull and create PR against"- pr_type:- required: false- type: string- default: "draft"- description: "The PR type that is going to be created (draft, ready)"- LLM_MODEL:- required: false- type: string- default: "anthropic/claude-sonnet-4-20250514"- LLM_API_VERSION:- required: false- type: string- default: ""- base_container_image:- required: false- type: string- default: ""- description: "Custom sandbox env"- runner:- required: false- type: string- default: "ubuntu-latest"- secrets:- LLM_MODEL:- required: false- LLM_API_KEY:- required: true- LLM_BASE_URL:- required: false- PAT_TOKEN:- required: false- PAT_USERNAME:- required: false-- issues:- types: [labeled]- pull_request:- types: [labeled]- issue_comment:- types: [created]- pull_request_review_comment:- types: [created]- pull_request_review:- types: [submitted]--permissions:- contents: write- pull-requests: write- issues: write--jobs:- auto-fix:- if: |- github.event_name == 'workflow_call' ||- github.event.label.name == 'fix-me' ||- github.event.label.name == 'fix-me-experimental' ||- (- ((github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment') &&- contains(github.event.comment.body, inputs.macro || '@openhands-agent') &&- (github.event.comment.author_association == 'OWNER' || github.event.comment.author_association == 'COLLABORATOR' || github.event.comment.author_association == 'MEMBER')- ) ||-- (github.event_name == 'pull_request_review' &&- contains(github.event.review.body, inputs.macro || '@openhands-agent') &&- (github.event.review.author_association == 'OWNER' || github.event.review.author_association == 'COLLABORATOR' || github.event.review.author_association == 'MEMBER')- )- )- runs-on: "${{ inputs.runner || 'ubuntu-latest' }}"- steps:- - name: Checkout repository- uses: actions/checkout@v6-- - name: Set up Python- uses: actions/setup-python@v6- with:- python-version: "3.12"- - name: Upgrade pip- run: |- python -m pip install --upgrade pip-- - name: Get latest versions and create requirements.txt- run: |- python -m pip index versions openhands-ai > openhands_versions.txt- OPENHANDS_VERSION=$(head -n 1 openhands_versions.txt | awk '{print $2}' | tr -d '()')-- # Create a new requirements.txt locally within the workflow, ensuring no reference to the repo's file- echo "openhands-ai==${OPENHANDS_VERSION}" > /tmp/requirements.txt- cat /tmp/requirements.txt-- - name: Cache pip dependencies- if: |- !(- github.event.label.name == 'fix-me-experimental' ||- (- (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment') &&- contains(github.event.comment.body, '@openhands-agent-exp')- ) ||- (- github.event_name == 'pull_request_review' &&- contains(github.event.review.body, '@openhands-agent-exp')- )- )- uses: actions/cache@v5- with:- path: ${{ env.pythonLocation }}/lib/python3.12/site-packages/*- key: ${{ runner.os }}-pip-openhands-resolver-${{ hashFiles('/tmp/requirements.txt') }}- restore-keys: |- ${{ runner.os }}-pip-openhands-resolver-${{ hashFiles('/tmp/requirements.txt') }}-- - name: Check required environment variables- env:- LLM_MODEL: ${{ secrets.LLM_MODEL || inputs.LLM_MODEL }}- LLM_API_KEY: ${{ secrets.LLM_API_KEY }}- LLM_BASE_URL: ${{ secrets.LLM_BASE_URL }}- LLM_API_VERSION: ${{ inputs.LLM_API_VERSION }}- PAT_TOKEN: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC }}- PAT_USERNAME: ${{ secrets.PAT_USERNAME }}- GITHUB_TOKEN: ${{ github.token }}- run: |- required_vars=("LLM_API_KEY")- for var in "${required_vars[@]}"; do- if [ -z "${!var}" ]; then- echo "Error: Required environment variable $var is not set."- exit 1- fi- done-- # Check optional variables and warn about fallbacks- if [ -z "$LLM_BASE_URL" ]; then- echo "Warning: LLM_BASE_URL is not set, will use default API endpoint"- fi-- if [ -z "$PAT_TOKEN" ]; then- echo "Warning: PAT_TOKEN is not set, falling back to GITHUB_TOKEN"- fi-- if [ -z "$PAT_USERNAME" ]; then- echo "Warning: PAT_USERNAME is not set, will use openhands-agent"- fi-- - name: Set environment variables- env:- REVIEW_BODY: ${{ github.event.review.body || '' }}- run: |- # Handle pull request events first- if [ -n "${{ github.event.pull_request.number }}" ]; then- echo "ISSUE_NUMBER=${{ github.event.pull_request.number }}" >> $GITHUB_ENV- echo "ISSUE_TYPE=pr" >> $GITHUB_ENV- # Handle pull request review events- elif [ -n "$REVIEW_BODY" ]; then- echo "ISSUE_NUMBER=${{ github.event.pull_request.number }}" >> $GITHUB_ENV- echo "ISSUE_TYPE=pr" >> $GITHUB_ENV- # Handle issue comment events that reference a PR- elif [ -n "${{ github.event.issue.pull_request }}" ]; then- echo "ISSUE_NUMBER=${{ github.event.issue.number }}" >> $GITHUB_ENV- echo "ISSUE_TYPE=pr" >> $GITHUB_ENV- # Handle regular issue events- else- echo "ISSUE_NUMBER=${{ github.event.issue.number }}" >> $GITHUB_ENV- echo "ISSUE_TYPE=issue" >> $GITHUB_ENV- fi-- if [ -n "$REVIEW_BODY" ]; then- echo "COMMENT_ID=${{ github.event.review.id || 'None' }}" >> $GITHUB_ENV- else- echo "COMMENT_ID=${{ github.event.comment.id || 'None' }}" >> $GITHUB_ENV- fi-- echo "MAX_ITERATIONS=${{ inputs.max_iterations || 50 }}" >> $GITHUB_ENV- echo "SANDBOX_ENV_GITHUB_TOKEN=${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC || github.token }}" >> $GITHUB_ENV- echo "SANDBOX_BASE_CONTAINER_IMAGE=${{ inputs.base_container_image }}" >> $GITHUB_ENV-- # Set branch variables- echo "TARGET_BRANCH=${{ inputs.target_branch || 'main' }}" >> $GITHUB_ENV-- - name: Comment on issue with start message- uses: actions/github-script@v9- with:- github-token: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC || github.token }}- script: |- const issueType = process.env.ISSUE_TYPE;- github.rest.issues.createComment({- issue_number: ${{ env.ISSUE_NUMBER }},- owner: context.repo.owner,- repo: context.repo.repo,- body: `[OpenHands](https://github.com/OpenHands/OpenHands) started fixing the ${issueType}! You can monitor the progress [here](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}).`- });-- - name: Install OpenHands- id: install_openhands- uses: actions/github-script@v9- env:- COMMENT_BODY: ${{ github.event.comment.body || '' }}- REVIEW_BODY: ${{ github.event.review.body || '' }}- LABEL_NAME: ${{ github.event.label.name || '' }}- EVENT_NAME: ${{ github.event_name }}- with:- script: |- const commentBody = process.env.COMMENT_BODY.trim();- const reviewBody = process.env.REVIEW_BODY.trim();- const labelName = process.env.LABEL_NAME.trim();- const eventName = process.env.EVENT_NAME.trim();- // Check conditions- const isExperimentalLabel = labelName === "fix-me-experimental";- const isIssueCommentExperimental =- (eventName === "issue_comment" || eventName === "pull_request_review_comment") &&- commentBody.includes("@openhands-agent-exp");- const isReviewCommentExperimental =- eventName === "pull_request_review" && reviewBody.includes("@openhands-agent-exp");-- // Set output variable- core.setOutput('isExperimental', isExperimentalLabel || isIssueCommentExperimental || isReviewCommentExperimental);-- // Perform package installation- if (isExperimentalLabel || isIssueCommentExperimental || isReviewCommentExperimental) {- console.log("Installing experimental OpenHands...");-- await exec.exec("pip install git+https://github.com/openhands/openhands.git");- } else {- console.log("Installing from requirements.txt...");-- await exec.exec("pip install -r /tmp/requirements.txt");- }-- - name: Attempt to resolve issue- env:- GITHUB_TOKEN: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC || github.token }}- GITHUB_USERNAME: ${{ secrets.PAT_USERNAME || 'openhands-agent' }}- GIT_USERNAME: ${{ secrets.PAT_USERNAME || 'openhands-agent' }}- LLM_MODEL: ${{ secrets.LLM_MODEL || inputs.LLM_MODEL }}- LLM_API_KEY: ${{ secrets.LLM_API_KEY }}- LLM_BASE_URL: ${{ secrets.LLM_BASE_URL }}- LLM_API_VERSION: ${{ inputs.LLM_API_VERSION }}- PYTHONPATH: ""- run: |- cd /tmp && python -m openhands.resolver.resolve_issue \- --selected-repo ${{ github.repository }} \- --issue-number ${{ env.ISSUE_NUMBER }} \- --issue-type ${{ env.ISSUE_TYPE }} \- --max-iterations ${{ env.MAX_ITERATIONS }} \- --comment-id ${{ env.COMMENT_ID }} \- --is-experimental ${{ steps.install_openhands.outputs.isExperimental }}-- - name: Check resolution result- id: check_result- run: |- if cd /tmp && grep -q '"success":true' output/output.jsonl; then- echo "RESOLUTION_SUCCESS=true" >> $GITHUB_OUTPUT- else- echo "RESOLUTION_SUCCESS=false" >> $GITHUB_OUTPUT- fi-- - name: Upload output.jsonl as artifact- uses: actions/upload-artifact@v7- if: always() # Upload even if the previous steps fail- with:- name: resolver-output- path: /tmp/output/output.jsonl- retention-days: 30 # Keep the artifact for 30 days-- - name: Create draft PR or push branch- if: always() # Create PR or branch even if the previous steps fail- env:- GITHUB_TOKEN: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC || github.token }}- GITHUB_USERNAME: ${{ secrets.PAT_USERNAME || 'openhands-agent' }}- GIT_USERNAME: ${{ secrets.PAT_USERNAME || 'openhands-agent' }}- LLM_MODEL: ${{ secrets.LLM_MODEL || inputs.LLM_MODEL }}- LLM_API_KEY: ${{ secrets.LLM_API_KEY }}- LLM_BASE_URL: ${{ secrets.LLM_BASE_URL }}- LLM_API_VERSION: ${{ inputs.LLM_API_VERSION }}- PYTHONPATH: ""- run: |- if [ "${{ steps.check_result.outputs.RESOLUTION_SUCCESS }}" == "true" ]; then- cd /tmp && python -m openhands.resolver.send_pull_request \- --issue-number ${{ env.ISSUE_NUMBER }} \- --target-branch ${{ env.TARGET_BRANCH }} \- --pr-type ${{ inputs.pr_type || 'draft' }} \- --reviewer ${{ github.actor }} | tee pr_result.txt && \- grep "PR created" pr_result.txt | sed 's/.*\///g' > pr_number.txt- else- cd /tmp && python -m openhands.resolver.send_pull_request \- --issue-number ${{ env.ISSUE_NUMBER }} \- --pr-type branch \- --send-on-failure | tee branch_result.txt && \- grep "branch created" branch_result.txt | sed 's/.*\///g; s/.expand=1//g' > branch_name.txt- fi-- # Step leaves comment for when agent is invoked on PR- - name: Analyze Push Logs (Updated PR or No Changes) # Skip comment if PR update was successful OR leave comment if the agent made no code changes- uses: actions/github-script@v9- if: always()- env:- AGENT_RESPONDED: ${{ env.AGENT_RESPONDED || 'false' }}- ISSUE_NUMBER: ${{ env.ISSUE_NUMBER }}- with:- github-token: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC || github.token }}- script: |- const fs = require('fs');- const issueNumber = process.env.ISSUE_NUMBER;- let logContent = '';-- try {- logContent = fs.readFileSync('/tmp/pr_result.txt', 'utf8').trim();- } catch (error) {- console.error('Error reading pr_result.txt file:', error);- }-- const noChangesMessage = `No changes to commit for issue #${issueNumber}. Skipping commit.`;-- // Check logs from send_pull_request.py (pushes code to GitHub)- if (logContent.includes("Updated pull request")) {- console.log("Updated pull request found. Skipping comment.");- process.env.AGENT_RESPONDED = 'true';- } else if (logContent.includes(noChangesMessage)) {- github.rest.issues.createComment({- issue_number: issueNumber,- owner: context.repo.owner,- repo: context.repo.repo,- body: `The workflow to fix this issue encountered an error. Openhands failed to create any code changes.`- });- process.env.AGENT_RESPONDED = 'true';- }-- # Step leaves comment for when agent is invoked on issue- - name: Comment on issue # Comment link to either PR or branch created by agent- uses: actions/github-script@v9- if: always() # Comment on issue even if the previous steps fail- env:- AGENT_RESPONDED: ${{ env.AGENT_RESPONDED || 'false' }}- ISSUE_NUMBER: ${{ env.ISSUE_NUMBER }}- RESOLUTION_SUCCESS: ${{ steps.check_result.outputs.RESOLUTION_SUCCESS }}- with:- github-token: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC || github.token }}- script: |- const fs = require('fs');- const path = require('path');- const issueNumber = process.env.ISSUE_NUMBER;- const success = process.env.RESOLUTION_SUCCESS === 'true';-- let prNumber = '';- let branchName = '';- let resultExplanation = '';-- try {- if (success) {- prNumber = fs.readFileSync('/tmp/pr_number.txt', 'utf8').trim();- } else {- branchName = fs.readFileSync('/tmp/branch_name.txt', 'utf8').trim();- }- } catch (error) {- console.error('Error reading file:', error);- }--- try {- if (!success){- // Read result_explanation from JSON file for failed resolution- const outputFilePath = path.resolve('/tmp/output/output.jsonl');- if (fs.existsSync(outputFilePath)) {- const outputContent = fs.readFileSync(outputFilePath, 'utf8');- const jsonLines = outputContent.split('\n').filter(line => line.trim() !== '');-- if (jsonLines.length > 0) {- // First entry in JSON lines has the key 'result_explanation'- const firstEntry = JSON.parse(jsonLines[0]);- resultExplanation = firstEntry.result_explanation || '';- }- }- }- } catch (error){- console.error('Error reading file:', error);- }-- // Check "success" log from resolver output- if (success && prNumber) {- github.rest.issues.createComment({- issue_number: issueNumber,- owner: context.repo.owner,- repo: context.repo.repo,- body: `A potential fix has been generated and a draft PR #${prNumber} has been created. Please review the changes.`- });- process.env.AGENT_RESPONDED = 'true';- } else if (!success && branchName) {- let commentBody = `An attempt was made to automatically fix this issue, but it was unsuccessful. A branch named '${branchName}' has been created with the attempted changes. You can view the branch [here](https://github.com/${context.repo.owner}/${context.repo.repo}/tree/${branchName}). Manual intervention may be required.`;-- if (resultExplanation) {- commentBody += `\n\nAdditional details about the failure:\n${resultExplanation}`;- }-- github.rest.issues.createComment({- issue_number: issueNumber,- owner: context.repo.owner,- repo: context.repo.repo,- body: commentBody- });- process.env.AGENT_RESPONDED = 'true';- }-- # Leave error comment when both PR/Issue comment handling fail- - name: Fallback Error Comment- uses: actions/github-script@v9- if: ${{ env.AGENT_RESPONDED == 'false' }} # Only run if no conditions were met in previous steps- env:- ISSUE_NUMBER: ${{ env.ISSUE_NUMBER }}- with:- github-token: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC || github.token }}- script: |- const issueNumber = process.env.ISSUE_NUMBER;-- github.rest.issues.createComment({- issue_number: issueNumber,- owner: context.repo.owner,- repo: context.repo.repo,- body: `The workflow to fix this issue encountered an error. Please check the [workflow logs](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}) for more information.`- });diff --git a/openhands/resolver/README.md b/openhands/resolver/README.mddeleted file mode 100644index 87b9a9b2a8..0000000000--- a/openhands/resolver/README.md+++ /dev/null@@ -1,218 +0,0 @@-# OpenHands GitHub, GitLab, Bitbucket & Azure DevOps Issue Resolver π--Need help resolving a GitHub, GitLab, Bitbucket, or Azure DevOps issue but don't have the time to do it yourself? Let an AI agent help you out!--This tool allows you to use open-source AI agents based on [OpenHands](https://github.com/openhands/openhands)-to attempt to resolve GitHub, GitLab, Bitbucket, and Azure DevOps issues automatically. While it can handle multiple issues, it's primarily designed-to help you resolve one issue at a time with high quality.--Getting started is simple - just follow the instructions below.--## Using the GitHub Actions Workflow--This repository includes a GitHub Actions workflow that can automatically attempt to fix individual issues labeled with 'fix-me'.-Follow these steps to use this workflow in your own repository:--1. [Create a personal access token](https://github.com/settings/tokens?type=beta) with read/write scope for "contents", "issues", "pull requests", and "workflows"-- Note: If you're working with an organizational repository, you may need to configure the organization's personal access token policy first. See [Setting a personal access token policy for your organization](https://docs.github.com/en/organizations/managing-programmatic-access-to-your-organization/setting-a-personal-access-token-policy-for-your-organization) for details.--2. Create an API key for the [Claude API](https://www.anthropic.com/api) (recommended) or another supported LLM service--3. Copy `examples/openhands-resolver.yml` to your repository's `.github/workflows/` directory--4. Configure repository permissions:- - Go to `Settings -> Actions -> General -> Workflow permissions`- - Select "Read and write permissions"- - Enable "Allow Github Actions to create and approve pull requests"-- Note: If the "Read and write permissions" option is greyed out:- - First check if permissions need to be set at the organization level- - If still greyed out at the organization level, permissions need to be set in the [Enterprise policy settings](https://docs.github.com/en/enterprise-cloud@latest/admin/enforcing-policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-github-actions-in-your-enterprise#enforcing-a-policy-for-workflow-permissions-in-your-enterprise)--5. Set up [GitHub secrets](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions):- - Required:- - `LLM_API_KEY`: Your LLM API key- - Optional:- - `PAT_USERNAME`: GitHub username for the personal access token- - `PAT_TOKEN`: The personal access token- - `LLM_BASE_URL`: Base URL for LLM API (only if using a proxy)-- Note: You can set these secrets at the organization level to use across multiple repositories.--6. Set up any [custom configurations required](https://docs.openhands.dev/usage/how-to/github-action#custom-configurations)--7. Usage:- There are two ways to trigger the OpenHands agent:-- a. Using the 'fix-me' label:- - Add the 'fix-me' label to any issue you want the AI to resolve- - The agent will consider all comments in the issue thread when resolving- - The workflow will:- 1. Attempt to resolve the issue using OpenHands- 2. Create a draft PR if successful, or push a branch if unsuccessful- 3. Comment on the issue with the results- 4. Remove the 'fix-me' label once processed-- b. Using `@openhands-agent` mention:- - Create a new comment containing `@openhands-agent` in any issue- - The agent will only consider the comment where it's mentioned- - The workflow will:- 1. Attempt to resolve the issue based on the specific comment- 2. Create a draft PR if successful, or push a branch if unsuccessful- 3. Comment on the issue with the results--Need help? Feel free to [open an issue](https://github.com/openhands/openhands/issues).--## Manual Installation--If you prefer to run the resolver programmatically instead of using GitHub Actions, follow these steps:--1. Install the package:--```bash-pip install openhands-ai-```--2. Create a GitHub, GitLab, Bitbucket, or Azure DevOps access token:- - Create a GitHub access token- - Visit [GitHub's token settings](https://github.com/settings/personal-access-tokens/new)- - Create a fine-grained token with these scopes:- - "Content"- - "Pull requests"- - "Issues"- - "Workflows"- - If you don't have push access to the target repo, you can fork it first-- - Create a GitLab access token- - Visit [GitLab's token settings](https://gitlab.com/-/user_settings/personal_access_tokens)- - Create a fine-grained token with these scopes:- - 'api'- - 'read_api'- - 'read_user'- - 'read_repository'- - 'write_repository'-- - Create a Bitbucket access token- - Visit [Bitbucket's app passwords settings](https://bitbucket.org/account/settings/app-passwords/)- - Create an app password with these scopes:- - 'Repositories: Read'- - 'Repositories: Write'- - 'Pull requests: Read'- - 'Pull requests: Write'- - 'Issues: Read'- - 'Issues: Write'-- - Create an Azure DevOps access token- - Visit [Azure DevOps token settings](https://dev.azure.com/{organization}/_usersSettings/tokens)- - Create a personal access token with these scopes:- - 'Code: Read & Write'- - 'Work Items: Read & Write'- - 'Pull Request: Read & Write'--3. Set up environment variables:--```bash--# GitHub credentials--export GITHUB_TOKEN="your-github-token"-export GIT_USERNAME="your-github-username" # Optional, defaults to token owner--# GitLab credentials if you're using GitLab repo--export GITLAB_TOKEN="your-gitlab-token"-export GIT_USERNAME="your-gitlab-username" # Optional, defaults to token owner--# Bitbucket credentials if you're using Bitbucket repo--export BITBUCKET_TOKEN="your-bitbucket-token"-export GIT_USERNAME="your-bitbucket-username" # Optional, defaults to token owner--# Azure DevOps credentials if you're using Azure DevOps repo--export AZURE_DEVOPS_TOKEN="your-azure-devops-token"-export GIT_USERNAME="your-azure-devops-username" # Optional, defaults to token owner--# LLM configuration--export LLM_MODEL="anthropic/claude-sonnet-4-20250514" # Recommended-export LLM_API_KEY="your-llm-api-key"-export LLM_BASE_URL="your-api-url" # Optional, for API proxies-```--Note: OpenHands works best with powerful models like Anthropic's Claude or OpenAI's GPT-4. While other models are supported, they may not perform as well for complex issue resolution.--## Resolving Issues--The resolver can automatically attempt to fix a single issue in your repository using the following command:--```bash-python -m openhands.resolver.resolve_issue --selected-repo [OWNER]/[REPO] --issue-number [NUMBER]-```--For instance, if you want to resolve issue #100 in this repo, you would run:--```bash-python -m openhands.resolver.resolve_issue --selected-repo openhands/openhands --issue-number 100-```--The output will be written to the `output/` directory.--If you've installed the package from source using poetry, you can use:--```bash-poetry run python openhands/resolver/resolve_issue.py --selected-repo openhands/openhands --issue-number 100-```--## Responding to PR Comments--The resolver can also respond to comments on pull requests using:--```bash-python -m openhands.resolver.send_pull_request --issue-number PR_NUMBER --issue-type pr-```--This functionality is available both through the GitHub Actions workflow and when running the resolver locally.--## Visualizing successful PRs--To find successful PRs, you can run the following command:--```bash-grep '"success":true' output/output.jsonl | sed 's/.*\("number":[0-9]*\).*/\1/g'-```--Then you can go through and visualize the ones you'd like.--```bash-python -m openhands.resolver.visualize_resolver_output --issue-number ISSUE_NUMBER --vis-method json-```--## Uploading PRs--If you find any PRs that were successful, you can upload them.-There are three ways you can upload:--1. `branch` - upload a branch without creating a PR-2. `draft` - create a draft PR-3. `ready` - create a non-draft PR that's ready for review--```bash-python -m openhands.resolver.send_pull_request --issue-number ISSUE_NUMBER --username YOUR_GIT_USERNAME --pr-type draft-```--If you want to upload to a fork, you can do so by specifying the `fork-owner`:--```bash-python -m openhands.resolver.send_pull_request --issue-number ISSUE_NUMBER --username YOUR_GIT_USERNAME --pr-type draft --fork-owner YOUR_GIT_USERNAME-```--## Providing Custom Instructions--You can customize how the AI agent approaches issue resolution by adding a repository microagent file at `.openhands/microagents/repo.md` in your repository. This file's contents will be automatically loaded in the prompt when working with your repository. For more information about repository microagents, see [Repository Instructions](https://github.com/OpenHands/OpenHands/tree/main/microagents#2-repository-instructions-private).--## Troubleshooting--If you have any issues, please open an issue on this GitHub, GitLab, or Bitbucket repo, we're happy to help!-Alternatively, you can [email us](mailto:[email protected]) or join the OpenHands Slack workspace (see [the README](/README.md) for an invite link).diff --git a/openhands/resolver/__init__.py b/openhands/resolver/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/openhands/resolver/examples/openhands-resolver.yml b/openhands/resolver/examples/openhands-resolver.ymldeleted file mode 100644index 66508c9990..0000000000--- a/openhands/resolver/examples/openhands-resolver.yml+++ /dev/null@@ -1,34 +0,0 @@-name: Resolve Issue with OpenHands--on:- issues:- types: [labeled]- pull_request:- types: [labeled]- issue_comment:- types: [created]- pull_request_review_comment:- types: [created]- pull_request_review:- types: [submitted]--permissions:- contents: write- pull-requests: write- issues: write--jobs:- call-openhands-resolver:- uses: OpenHands/OpenHands/.github/workflows/openhands-resolver.yml@main- with:- macro: ${{ vars.OPENHANDS_MACRO || '@openhands-agent' }}- max_iterations: ${{ fromJson(vars.OPENHANDS_MAX_ITER || 50) }}- base_container_image: ${{ vars.OPENHANDS_BASE_CONTAINER_IMAGE || '' }}- LLM_MODEL: ${{ vars.LLM_MODEL || 'anthropic/claude-sonnet-4-20250514' }}- target_branch: ${{ vars.TARGET_BRANCH || 'main' }}- runner: ${{ vars.TARGET_RUNNER }}- secrets:- PAT_TOKEN: ${{ secrets.PAT_TOKEN }}- PAT_USERNAME: ${{ secrets.PAT_USERNAME }}- LLM_API_KEY: ${{ secrets.LLM_API_KEY }}- LLM_BASE_URL: ${{ secrets.LLM_BASE_URL }}diff --git a/openhands/resolver/interfaces/azure_devops.py b/openhands/resolver/interfaces/azure_devops.pydeleted file mode 100644index 8cddc8c92d..0000000000--- a/openhands/resolver/interfaces/azure_devops.py+++ /dev/null@@ -1,434 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import base64-import re-from typing import Any--import httpx--from openhands.resolver.interfaces.issue import (- Issue,- IssueHandlerInterface,- ReviewThread,-)---class AzureDevOpsIssueHandler(IssueHandlerInterface):- def __init__(- self,- token: str,- organization: str,- project: str,- repository: str,- ):- self.token = token- self.organization = organization- self.project = project- self.repository = repository- self.owner = f'{organization}/{project}'- self.base_api_url = f'https://dev.azure.com/{organization}/{project}/_apis'- self.repo_api_url = f'{self.base_api_url}/git/repositories/{repository}'- self.work_items_api_url = f'{self.base_api_url}/wit'- self.default_branch = 'main'-- def set_owner(self, owner: str) -> None:- """Set the owner of the repository."""- self.owner = owner- parts = owner.split('/')- if len(parts) >= 2:- self.organization = parts[0]- self.project = parts[1]- self.base_api_url = (- f'https://dev.azure.com/{self.organization}/{self.project}/_apis'- )- self.repo_api_url = (- f'{self.base_api_url}/git/repositories/{self.repository}'- )- self.work_items_api_url = f'{self.base_api_url}/wit'-- def get_headers(self) -> dict[str, str]:- """Get the headers for the Azure DevOps API."""- auth_str = base64.b64encode(f':{self.token}'.encode()).decode()- return {- 'Authorization': f'Basic {auth_str}',- 'Content-Type': 'application/json',- 'Accept': 'application/json',- }-- def download_issues(self) -> list[Any]:- """Download issues from Azure DevOps."""- # Use WIQL to query for active work items- wiql_url = f'{self.work_items_api_url}/wiql?api-version=7.1'- wiql_query = {- 'query': "SELECT [System.Id], [System.Title], [System.State] FROM WorkItems WHERE [System.State] = 'Active' ORDER BY [System.CreatedDate] DESC"- }-- response = httpx.post(wiql_url, headers=self.get_headers(), json=wiql_query)- response.raise_for_status()-- work_item_references = response.json().get('workItems', [])-- # Get details for each work item- work_items = []- for work_item_ref in work_item_references:- work_item_id = work_item_ref.get('id')- work_item_url = f'{self.work_items_api_url}/workitems/{work_item_id}?api-version=7.1&$expand=all'-- item_response = httpx.get(work_item_url, headers=self.get_headers())- item_response.raise_for_status()-- work_items.append(item_response.json())-- return work_items-- def get_issue_comments(- self, issue_number: int, comment_id: int | None = None- ) -> list[str] | None:- """Get comments for an issue."""- comments_url = f'{self.work_items_api_url}/workitems/{issue_number}/comments?api-version=7.1-preview.3'-- response = httpx.get(comments_url, headers=self.get_headers())- response.raise_for_status()-- comments_data = response.json().get('comments', [])-- if comment_id is not None:- # Return a specific comment- for comment in comments_data:- if comment.get('id') == comment_id:- return [comment.get('text', '')]- return None-- # Return all comments- return [comment.get('text', '') for comment in comments_data]-- def get_base_url(self) -> str:- """Get the base URL for the Azure DevOps repository."""- return f'https://dev.azure.com/{self.organization}/{self.project}'-- def get_branch_url(self, branch_name: str) -> str:- """Get the URL for a branch."""- return f'{self.get_base_url()}/_git/{self.repository}?version=GB{branch_name}'-- def get_download_url(self) -> str:- """Get the download URL for the repository."""- return f'{self.get_base_url()}/_git/{self.repository}'-- def get_clone_url(self) -> str:- """Get the clone URL for the repository."""- return f'https://dev.azure.com/{self.organization}/{self.project}/_git/{self.repository}'-- def get_pull_url(self, pr_number: int) -> str:- """Get the URL for a pull request."""- return f'{self.get_base_url()}/_git/{self.repository}/pullrequest/{pr_number}'-- def get_graphql_url(self) -> str:- """Get the GraphQL URL for Azure DevOps."""- return f'https://dev.azure.com/{self.organization}/_apis/graphql?api-version=7.1-preview.1'-- def get_compare_url(self, branch_name: str) -> str:- """Get the URL to compare branches."""- return f'{self.get_base_url()}/_git/{self.repository}/branches?baseVersion=GB{self.default_branch}&targetVersion=GB{branch_name}&_a=files'-- def get_branch_name(self, base_branch_name: str) -> str:- """Generate a branch name for a new pull request."""- return f'openhands/issue-{base_branch_name}'-- def get_default_branch_name(self) -> str:- """Get the default branch name for the repository."""- # Get repository details to find the default branch- response = httpx.get(- f'{self.repo_api_url}?api-version=7.1', headers=self.get_headers()- )- response.raise_for_status()-- repo_data = response.json()- default_branch = repo_data.get('defaultBranch', 'refs/heads/main')-- # Remove 'refs/heads/' prefix- return default_branch.replace('refs/heads/', '')-- def branch_exists(self, branch_name: str) -> bool:- """Check if a branch exists."""- # List all branches and check if the branch exists- response = httpx.get(- f'{self.repo_api_url}/refs?filter=heads/{branch_name}&api-version=7.1',- headers=self.get_headers(),- )- response.raise_for_status()-- refs = response.json().get('value', [])- return len(refs) > 0-- def reply_to_comment(self, pr_number: int, comment_id: str, reply: str) -> None:- """Reply to a comment on a pull request."""- # Get the thread ID from the comment ID- threads_url = (- f'{self.repo_api_url}/pullRequests/{pr_number}/threads?api-version=7.1'- )-- response = httpx.get(threads_url, headers=self.get_headers())- response.raise_for_status()-- threads = response.json().get('value', [])- thread_id = None-- for thread in threads:- for comment in thread.get('comments', []):- if str(comment.get('id')) == comment_id:- thread_id = thread.get('id')- break- if thread_id:- break-- if not thread_id:- raise ValueError(f'Comment ID {comment_id} not found in PR {pr_number}')-- # Add a comment to the thread- comment_url = f'{self.repo_api_url}/pullRequests/{pr_number}/threads/{thread_id}/comments?api-version=7.1'-- comment_data = {- 'content': reply,- 'parentCommentId': int(comment_id),- }-- response = httpx.post(- comment_url, headers=self.get_headers(), json=comment_data- )- response.raise_for_status()-- def send_comment_msg(self, issue_number: int, msg: str) -> None:- """Send a comment to an issue."""- comment_url = f'{self.work_items_api_url}/workitems/{issue_number}/comments?api-version=7.1-preview.3'-- comment_data = {- 'text': msg,- }-- response = httpx.post(- comment_url, headers=self.get_headers(), json=comment_data- )- response.raise_for_status()-- def get_authorize_url(self) -> str:- """Get the authorization URL for Azure DevOps."""- return 'https://app.vsaex.visualstudio.com/app/register'-- def create_pull_request(self, data: dict[str, Any] | None = None) -> dict[str, Any]:- """Create a pull request."""- if data is None:- data = {}-- source_branch = data.get('source_branch')- target_branch = data.get('target_branch', self.default_branch)- title = data.get('title', 'Pull request created by OpenHands')- description = data.get('description', '')-- pr_data = {- 'sourceRefName': f'refs/heads/{source_branch}',- 'targetRefName': f'refs/heads/{target_branch}',- 'title': title,- 'description': description,- }-- response = httpx.post(- f'{self.repo_api_url}/pullrequests?api-version=7.1',- headers=self.get_headers(),- json=pr_data,- )- response.raise_for_status()-- pr_response = response.json()-- return {- 'id': pr_response.get('pullRequestId'),- 'number': pr_response.get('pullRequestId'),- 'url': pr_response.get('url'),- }-- def request_reviewers(self, reviewer: str, pr_number: int) -> None:- """Request reviewers for a pull request."""- # Get the reviewer's ID- reviewer_url = f'https://vssps.dev.azure.com/{self.organization}/_apis/graph/users?api-version=7.1-preview.1'-- response = httpx.get(reviewer_url, headers=self.get_headers())- response.raise_for_status()-- users = response.json().get('value', [])- reviewer_id = None-- for user in users:- if (- user.get('displayName') == reviewer- or user.get('mailAddress') == reviewer- ):- reviewer_id = user.get('descriptor')- break-- if not reviewer_id:- raise ValueError(f'Reviewer {reviewer} not found')-- # Add reviewer to the pull request- reviewers_url = f'{self.repo_api_url}/pullRequests/{pr_number}/reviewers/{reviewer_id}?api-version=7.1'-- reviewer_data = {- 'vote': 0, # No vote yet- }-- response = httpx.put(- reviewers_url, headers=self.get_headers(), json=reviewer_data- )- response.raise_for_status()-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- """Get context from external issue references."""- context = []-- # Add issue body- if issue_body:- context.append(f'Issue description:\n{issue_body}')-- # Add thread comments- if thread_comments:- context.append('Thread comments:\n' + '\n'.join(thread_comments))-- # Add review comments- if review_comments:- context.append('Review comments:\n' + '\n'.join(review_comments))-- # Add review threads- if review_threads:- for thread in review_threads:- context.append(- f'Review thread for files {", ".join(thread.files)}:\n{thread.comment}'- )-- return context-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- """Download issues from Azure DevOps and convert them to the Issue model."""- if issue_numbers is None:- # Download all issues- work_items = self.download_issues()- else:- # Download specific issues- work_items = []- for issue_number in issue_numbers:- work_item_url = f'{self.work_items_api_url}/workitems/{issue_number}?api-version=7.1&$expand=all'-- response = httpx.get(work_item_url, headers=self.get_headers())- response.raise_for_status()-- work_items.append(response.json())-- issues = []- for work_item in work_items:- # Get basic issue information- issue_number = work_item.get('id')- title = work_item.get('fields', {}).get('System.Title', '')- description = work_item.get('fields', {}).get('System.Description', '')-- # Get comments- thread_comments = self.get_issue_comments(issue_number, comment_id)-- # Check if this is a pull request work item- is_pr = False- pr_number = None- head_branch = None- base_branch = None-- # Look for PR links in the work item relations- for relation in work_item.get('relations', []):- if relation.get(- 'rel'- ) == 'ArtifactLink' and 'pullrequest' in relation.get('url', ''):- is_pr = True- # Extract PR number from URL- pr_url = relation.get('url', '')- pr_match = re.search(r'pullRequests/(\d+)', pr_url)- if pr_match:- pr_number = int(pr_match.group(1))- break-- # If this is a PR, get the branch information- if is_pr and pr_number:- pr_url = f'{self.repo_api_url}/pullRequests/{pr_number}?api-version=7.1'-- pr_response = httpx.get(pr_url, headers=self.get_headers())- pr_response.raise_for_status()-- pr_data = pr_response.json()- head_branch = pr_data.get('sourceRefName', '').replace(- 'refs/heads/', ''- )- base_branch = pr_data.get('targetRefName', '').replace(- 'refs/heads/', ''- )-- # Get PR review comments- review_comments = []- review_threads = []-- threads_url = f'{self.repo_api_url}/pullRequests/{pr_number}/threads?api-version=7.1'-- threads_response = httpx.get(threads_url, headers=self.get_headers())- threads_response.raise_for_status()-- threads = threads_response.json().get('value', [])-- for thread in threads:- thread_comments = [- comment.get('content', '')- for comment in thread.get('comments', [])- ]- review_comments.extend(thread_comments)-- # Get files associated with this thread- thread_files = []- if thread.get('threadContext', {}).get('filePath'):- thread_files.append(- thread.get('threadContext', {}).get('filePath')- )-- if thread_comments:- review_threads.append(- ReviewThread(- comment='\n'.join(thread_comments),- files=thread_files,- )- )-- # Create the Issue object- issue = Issue(- owner=self.owner,- repo=self.repository,- number=issue_number,- title=title,- body=description,- thread_comments=thread_comments,- closing_issues=None,- review_comments=review_comments if is_pr else None,- review_threads=review_threads if is_pr else None,- thread_ids=None,- head_branch=head_branch,- base_branch=base_branch,- )-- issues.append(issue)-- return issuesdiff --git a/openhands/resolver/interfaces/bitbucket.py b/openhands/resolver/interfaces/bitbucket.pydeleted file mode 100644index db9dae2caa..0000000000--- a/openhands/resolver/interfaces/bitbucket.py+++ /dev/null@@ -1,527 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import base64-from typing import Any--import httpx--from openhands.core.logger import openhands_logger as logger-from openhands.resolver.interfaces.issue import (- Issue,- IssueHandlerInterface,- ReviewThread,-)-from openhands.resolver.utils import extract_issue_references-from openhands.utils.http_session import httpx_verify_option---class BitbucketIssueHandler(IssueHandlerInterface):- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'bitbucket.org',- ):- """Initialize a Bitbucket issue handler.-- Args:- owner: The workspace of the repository- repo: The name of the repository- token: The Bitbucket API token- username: Optional Bitbucket username- base_domain: The domain for Bitbucket Server (default: "bitbucket.org")- """- self.owner = owner- self.repo = repo- self.token = token- self.username = username- self.base_domain = base_domain- self.base_url = self.get_base_url()- self.download_url = self.get_download_url()- self.clone_url = self.get_clone_url()- self.headers = self.get_headers()-- def set_owner(self, owner: str) -> None:- self.owner = owner-- def get_headers(self) -> dict[str, str]:- # Check if the token contains a colon, which indicates it's in username:password format- if ':' in self.token:- auth_str = base64.b64encode(self.token.encode()).decode()- return {- 'Authorization': f'Basic {auth_str}',- 'Accept': 'application/json',- }- else:- return {- 'Authorization': f'Bearer {self.token}',- 'Accept': 'application/json',- }-- def get_base_url(self) -> str:- """Get the base URL for the Bitbucket API."""- return f'https://api.{self.base_domain}/2.0'-- def get_download_url(self) -> str:- """Get the download URL for the repository."""- return f'https://{self.base_domain}/{self.owner}/{self.repo}/get/master.zip'-- def get_clone_url(self) -> str:- """Get the clone URL for the repository."""- return f'https://{self.base_domain}/{self.owner}/{self.repo}.git'-- def get_repo_url(self) -> str:- """Get the URL for the repository."""- return f'https://{self.base_domain}/{self.owner}/{self.repo}'-- def get_issue_url(self, issue_number: int) -> str:- """Get the URL for an issue."""- return f'{self.get_repo_url()}/issues/{issue_number}'-- def get_pr_url(self, pr_number: int) -> str:- """Get the URL for a pull request."""- return f'{self.get_repo_url()}/pull-requests/{pr_number}'-- async def get_issue(self, issue_number: int) -> Issue:- """Get an issue from Bitbucket.-- Args:- issue_number: The issue number-- Returns:- An Issue object- """- url = f'{self.base_url}/repositories/{self.owner}/{self.repo}/issues/{issue_number}'- async with httpx.AsyncClient(verify=httpx_verify_option()) as client:- response = await client.get(url, headers=self.headers)- response.raise_for_status()- data = response.json()-- # Create a basic Issue object with required fields- issue = Issue(- owner=self.owner,- repo=self.repo,- number=data.get('id'),- title=data.get('title', ''),- body=data.get('content', {}).get('raw', ''),- )-- return issue-- def create_pr(- self,- title: str,- body: str,- head: str,- base: str,- ) -> str:- """Create a pull request.-- Args:- title: The title of the pull request- body: The body of the pull request- head: The head branch- base: The base branch-- Returns:- The URL of the created pull request- """- url = f'{self.base_url}/repositories/{self.owner}/{self.repo}/pullrequests'-- payload = {- 'title': title,- 'description': body,- 'source': {'branch': {'name': head}},- 'destination': {'branch': {'name': base}},- 'close_source_branch': False,- }-- response = httpx.post(url, headers=self.headers, json=payload)- response.raise_for_status()- data = response.json()-- return data.get('links', {}).get('html', {}).get('href', '')-- def download_issues(self) -> list[Any]:- """Download all issues from the repository.-- Returns:- A list of issues- """- logger.warning('BitbucketIssueHandler.download_issues not implemented')- return []-- def get_issue_comments(- self, issue_number: int, comment_id: int | None = None- ) -> list[str] | None:- """Get comments for an issue.-- Args:- issue_number: The issue number- comment_id: The comment ID (optional)-- Returns:- A list of comments- """- logger.warning('BitbucketIssueHandler.get_issue_comments not implemented')- return []-- def get_branch_url(self, branch_name: str) -> str:- """Get the URL for a branch.-- Args:- branch_name: The branch name-- Returns:- The URL for the branch- """- return (- f'https://{self.base_domain}/{self.owner}/{self.repo}/branch/{branch_name}'- )-- def get_compare_url(self, branch_name: str) -> str:- """Get the URL for comparing branches.-- Args:- branch_name: The branch name-- Returns:- The URL for comparing branches- """- return f'https://{self.base_domain}/{self.owner}/{self.repo}/compare/master...{branch_name}'-- def get_authorize_url(self) -> str:- """Get the URL for authorization.-- Returns:- The URL for authorization- """- return f'https://oauth2:{self.token}@{self.base_domain}/'-- def get_pull_url(self, pr_number: int) -> str:- """Get the URL for a pull request.-- Args:- pr_number: The pull request number-- Returns:- The URL for the pull request- """- return f'https://{self.base_domain}/{self.owner}/{self.repo}/pull-requests/{pr_number}'-- def get_branch_name(self, base_branch_name: str) -> str:- """Get a unique branch name.-- Args:- base_branch_name: The base branch name-- Returns:- A unique branch name- """- return f'{base_branch_name}-{self.owner}'-- def branch_exists(self, branch_name: str) -> bool:- """Check if a branch exists.-- Args:- branch_name: The branch name-- Returns:- True if the branch exists, False otherwise- """- logger.warning('BitbucketIssueHandler.branch_exists not implemented')- return False-- def get_default_branch_name(self) -> str:- """Get the default branch name.-- Returns:- The default branch name- """- return 'master'-- def create_pull_request(self, data: dict[str, Any] | None = None) -> dict[str, Any]:- """Create a pull request.-- Args:- data: The pull request data-- Returns:- The created pull request- """- if data is None:- data = {}-- title = data.get('title', '')- description = data.get('description', '')- source_branch = data.get('source_branch', '')- target_branch = data.get('target_branch', '')-- url = f'{self.base_url}/repositories/{self.owner}/{self.repo}/pullrequests'-- payload = {- 'title': title,- 'description': description,- 'source': {'branch': {'name': source_branch}},- 'destination': {'branch': {'name': target_branch}},- 'close_source_branch': False,- }-- response = httpx.post(url, headers=self.headers, json=payload)- response.raise_for_status()- data = response.json()-- # Ensure data is not None before accessing it- if data is None:- data = {}-- return {- 'html_url': data.get('links', {}).get('html', {}).get('href', ''),- 'number': data.get('id', 0),- }-- def request_reviewers(self, reviewer: str, pr_number: int) -> None:- """Request reviewers for a pull request.-- Args:- reviewer: The reviewer- pr_number: The pull request number- """- logger.warning('BitbucketIssueHandler.request_reviewers not implemented')-- def send_comment_msg(self, issue_number: int, msg: str) -> None:- """Send a comment to an issue.-- Args:- issue_number: The issue number- msg: The message- """- url = f'{self.base_url}/repositories/{self.owner}/{self.repo}/pullrequests/{issue_number}/comments'-- payload = {'content': {'raw': msg}}-- response = httpx.post(url, headers=self.headers, json=payload)- response.raise_for_status()-- def get_issue_thread_comments(self, issue_number: int) -> list[str]:- """Get thread comments for an issue.-- Args:- issue_number: The issue number-- Returns:- A list of thread comments- """- logger.warning(- 'BitbucketIssueHandler.get_issue_thread_comments not implemented'- )- return []-- def get_issue_review_comments(self, issue_number: int) -> list[str]:- """Get review comments for an issue.-- Args:- issue_number: The issue number-- Returns:- A list of review comments- """- logger.warning(- 'BitbucketIssueHandler.get_issue_review_comments not implemented'- )- return []-- def get_issue_review_threads(self, issue_number: int) -> list[ReviewThread]:- """Get review threads for an issue.-- Args:- issue_number: The issue number-- Returns:- A list of review threads- """- logger.warning('BitbucketIssueHandler.get_issue_review_threads not implemented')- return []-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- """Get context from external issue references.-- Args:- closing_issues: List of closing issue references- closing_issue_numbers: List of closing issue numbers- issue_body: The issue body- review_comments: List of review comments- review_threads: List of review threads- thread_comments: List of thread comments-- Returns:- Context from external issue references- """- new_issue_references = []-- if issue_body:- new_issue_references.extend(extract_issue_references(issue_body))-- if review_comments:- for comment in review_comments:- new_issue_references.extend(extract_issue_references(comment))-- if review_threads:- for review_thread in review_threads:- new_issue_references.extend(- extract_issue_references(review_thread.comment)- )-- if thread_comments:- for thread_comment in thread_comments:- new_issue_references.extend(extract_issue_references(thread_comment))-- non_duplicate_references = set(new_issue_references)- unique_issue_references = non_duplicate_references.difference(- closing_issue_numbers- )-- for issue_number in unique_issue_references:- try:- url = f'{self.base_url}/repositories/{self.owner}/{self.repo}/issues/{issue_number}'- response = httpx.get(url, headers=self.headers)- response.raise_for_status()- issue_data = response.json()- issue_body = issue_data.get('content', {}).get('raw', '')- if issue_body:- closing_issues.append(issue_body)- except httpx.HTTPError as e:- logger.warning(f'Failed to fetch issue {issue_number}: {str(e)}')-- return closing_issues-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- """Get converted issues.-- Args:- issue_numbers: List of issue numbers- comment_id: The comment ID-- Returns:- A list of converted issues- """- if not issue_numbers:- raise ValueError('Unspecified issue numbers')-- all_issues = self.download_issues()- logger.info(f'Limiting resolving to issues {issue_numbers}.')- all_issues = [issue for issue in all_issues if issue.get('id') in issue_numbers]-- converted_issues = []- for issue in all_issues:- # For PRs, body can be None- if any([issue.get(key) is None for key in ['id', 'title']]):- logger.warning(f'Skipping #{issue} as it is missing id or title.')- continue-- # Handle None body for PRs- body = (- issue.get('content', {}).get('raw', '')- if issue.get('content') is not None- else ''- )-- # Placeholder for PR metadata- closing_issues: list[str] = []- review_comments: list[str] = []- review_threads: list[ReviewThread] = []- thread_ids: list[str] = []- head_branch = issue.get('source', {}).get('branch', {}).get('name', '')- thread_comments: list[str] = []-- issue_details = Issue(- owner=self.owner,- repo=self.repo,- number=issue['id'],- title=issue['title'],- body=body,- closing_issues=closing_issues,- review_comments=review_comments,- review_threads=review_threads,- thread_ids=thread_ids,- head_branch=head_branch,- thread_comments=thread_comments,- )-- converted_issues.append(issue_details)-- return converted_issues-- def get_graphql_url(self) -> str:- """Get the GraphQL URL.-- Returns:- The GraphQL URL- """- return f'https://api.{self.base_domain}/graphql'-- def reply_to_comment(self, pr_number: int, comment_id: str, reply: str) -> None:- """Reply to a comment.-- Args:- pr_number: The pull request number- comment_id: The comment ID- reply: The reply message- """- url = f'{self.base_url}/repositories/{self.owner}/{self.repo}/pullrequests/{pr_number}/comments/{comment_id}'-- payload = {'content': {'raw': reply}}-- response = httpx.post(url, headers=self.headers, json=payload)- response.raise_for_status()-- def get_issue_references(self, body: str) -> list[int]:- """Extract issue references from a string.-- Args:- body: The string to extract issue references from-- Returns:- A list of issue numbers- """- return extract_issue_references(body)---class BitbucketPRHandler(BitbucketIssueHandler):- """Handler for Bitbucket pull requests, extending the issue handler."""-- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'bitbucket.org',- ):- """Initialize a Bitbucket PR handler.-- Args:- owner: The workspace of the repository- repo: The name of the repository- token: The Bitbucket API token- username: Optional Bitbucket username- base_domain: The domain for Bitbucket Server (default: "bitbucket.org")- """- super().__init__(owner, repo, token, username, base_domain)diff --git a/openhands/resolver/interfaces/bitbucket_data_center.py b/openhands/resolver/interfaces/bitbucket_data_center.pydeleted file mode 100644index 9931ef7493..0000000000--- a/openhands/resolver/interfaces/bitbucket_data_center.py+++ /dev/null@@ -1,359 +0,0 @@-import base64-from typing import Any-from urllib.parse import quote--import httpx--from openhands.core.logger import openhands_logger as logger-from openhands.resolver.interfaces.issue import (- Issue,- IssueHandlerInterface,- ReviewThread,-)-from openhands.resolver.utils import extract_issue_references-from openhands.utils.async_utils import GENERAL_TIMEOUT, call_async_from_sync-from openhands.utils.http_session import httpx_verify_option---class BitbucketDCIssueHandler(IssueHandlerInterface):- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'bitbucket.example.com',- ):- """Initialize a Bitbucket Data Center issue handler.-- Args:- owner: The project key of the repository- repo: The slug of the repository- token: The Bitbucket DC API token (user:password or user:token format)- username: Optional username (used when token is a bare API token)- base_domain: The hostname of the Bitbucket DC instance- """- self.owner = owner- self.repo = repo- self.token = token- self.username = username- self.base_domain = base_domain- self.base_url = self.get_base_url()- self.download_url = self.get_download_url()- self.clone_url = self.get_clone_url()- self.headers = self.get_headers()-- def set_owner(self, owner: str) -> None:- self.owner = owner-- def get_headers(self) -> dict[str, str]:- # DC always uses HTTP Basic auth- if ':' in self.token:- auth_str = base64.b64encode(self.token.encode()).decode()- elif self.username:- creds = f'{self.username}:{self.token}'- auth_str = base64.b64encode(creds.encode()).decode()- else:- auth_str = base64.b64encode(self.token.encode()).decode()- return {- 'Authorization': f'Basic {auth_str}',- 'Accept': 'application/json',- }-- def get_base_url(self) -> str:- return f'https://{self.base_domain}/rest/api/1.0'-- def _get_repo_api_base(self) -> str:- return f'{self.base_url}/projects/{self.owner}/repos/{self.repo}'-- def get_download_url(self) -> str:- return (- f'https://{self.base_domain}/rest/api/latest'- f'/projects/{self.owner}/repos/{self.repo}/archive?format=zip'- )-- def get_clone_url(self) -> str:- return f'https://{self.base_domain}/scm/{self.owner.lower()}/{self.repo}.git'-- def get_repo_url(self) -> str:- return f'https://{self.base_domain}/projects/{self.owner}/repos/{self.repo}'-- def get_issue_url(self, issue_number: int) -> str:- # DC has no issue tracker; use pull-requests URL- return f'{self.get_repo_url()}/pull-requests/{issue_number}'-- def get_pr_url(self, pr_number: int) -> str:- return f'{self.get_repo_url()}/pull-requests/{pr_number}'-- def get_pull_url(self, pr_number: int) -> str:- return f'{self.get_repo_url()}/pull-requests/{pr_number}'-- def get_branch_url(self, branch_name: str) -> str:- return f'{self.get_repo_url()}/browse?at=refs/heads/{branch_name}'-- def get_compare_url(self, branch_name: str) -> str:- default_branch = self.get_default_branch_name()- return (- f'{self.get_repo_url()}/compare/commits'- f'?sourceBranch=refs/heads/{branch_name}'- f'&targetBranch=refs/heads/{default_branch}'- )-- def get_authorize_url(self) -> str:- if ':' in self.token:- user, _, token = self.token.partition(':')- creds = f'{quote(user, safe="")}:{quote(token, safe="")}'- elif self.username:- creds = f'{quote(self.username, safe="")}:{quote(self.token, safe="")}'- else:- creds = quote(self.token, safe='')- return f'https://{creds}@{self.base_domain}/'-- def get_graphql_url(self) -> str:- # DC has no GraphQL API; return a placeholder- return f'https://{self.base_domain}/rest/api/1.0'-- def get_branch_name(self, base_branch_name: str) -> str:- return f'{base_branch_name}-{self.owner}'-- async def get_issue(self, issue_number: int) -> Issue:- """Fetch a Bitbucket DC pull request as an Issue.-- Args:- issue_number: The pull request ID-- Returns:- An Issue object populated from the DC pull request response- """- url = f'{self._get_repo_api_base()}/pull-requests/{issue_number}'- async with httpx.AsyncClient(verify=httpx_verify_option()) as client:- response = await client.get(url, headers=self.headers)- response.raise_for_status()- data = response.json()-- head_branch = data.get('fromRef', {}).get('displayId', '')- base_branch = data.get('toRef', {}).get('displayId', '')-- return Issue(- owner=self.owner,- repo=self.repo,- number=data.get('id'),- title=data.get('title', ''),- body=data.get('description', ''),- head_branch=head_branch,- base_branch=base_branch,- )-- def create_pr(- self,- title: str,- body: str,- head: str,- base: str,- ) -> str:- """Create a pull request on Bitbucket DC.-- Args:- title: PR title- body: PR description- head: Source branch name- base: Target branch name-- Returns:- The URL of the created pull request- """- result = self.create_pull_request(- {- 'title': title,- 'description': body,- 'source_branch': head,- 'target_branch': base,- }- )- return result.get('html_url', '')-- def create_pull_request(self, data: dict[str, Any] | None = None) -> dict[str, Any]:- """Create a pull request and return html_url and number.-- Args:- data: Dict with keys title, description, source_branch, target_branch-- Returns:- Dict with 'html_url' and 'number' keys- """- if data is None:- data = {}-- title = data.get('title', '')- description = data.get('description', '')- source_branch = data.get('source_branch', '')- target_branch = data.get('target_branch', '')-- url = f'{self._get_repo_api_base()}/pull-requests'- payload = {- 'title': title,- 'description': description,- 'fromRef': {- 'id': f'refs/heads/{source_branch}',- 'repository': {- 'slug': self.repo,- 'project': {'key': self.owner},- },- },- 'toRef': {- 'id': f'refs/heads/{target_branch}',- 'repository': {- 'slug': self.repo,- 'project': {'key': self.owner},- },- },- }- response = httpx.post(- url, headers=self.headers, json=payload, verify=httpx_verify_option()- )- response.raise_for_status()- resp_data = response.json()-- links = resp_data.get('links', {}).get('self', [])- html_url = links[0].get('href', '') if links else ''-- return {- 'html_url': html_url,- 'number': resp_data.get('id', 0),- }-- def send_comment_msg(self, issue_number: int, msg: str) -> None:- url = f'{self._get_repo_api_base()}/pull-requests/{issue_number}/comments'- payload = {'text': msg}- response = httpx.post(- url, headers=self.headers, json=payload, verify=httpx_verify_option()- )- response.raise_for_status()-- def reply_to_comment(self, pr_number: int, comment_id: str, reply: str) -> None:- url = f'{self._get_repo_api_base()}/pull-requests/{pr_number}/comments'- payload = {- 'text': reply,- 'parent': {'id': int(comment_id)},- }- response = httpx.post(- url, headers=self.headers, json=payload, verify=httpx_verify_option()- )- response.raise_for_status()-- def branch_exists(self, branch_name: str) -> bool:- url = f'{self._get_repo_api_base()}/branches'- try:- response = httpx.get(- url,- headers=self.headers,- params={'filterText': branch_name, 'limit': '1'},- verify=httpx_verify_option(),- )- response.raise_for_status()- data = response.json()- values = data.get('values', [])- return any(v.get('displayId') == branch_name for v in values)- except httpx.HTTPError as e:- logger.warning(f'Failed to check branch existence: {e}')- return False-- def get_default_branch_name(self) -> str:- url = self._get_repo_api_base()- try:- response = httpx.get(- url, headers=self.headers, verify=httpx_verify_option()- )- response.raise_for_status()- data = response.json()- default_branch = data.get('defaultBranch', {})- if default_branch:- display_id = default_branch.get('displayId', '')- if display_id:- if display_id.startswith('refs/heads/'):- return display_id[len('refs/heads/') :]- return display_id- except httpx.HTTPError as e:- logger.warning(f'Failed to get default branch name: {e}')- return 'master'-- def download_issues(self) -> list[Any]:- logger.warning(- 'BitbucketDCIssueHandler.download_issues not implemented; '- 'use get_issue() to fetch individual pull requests'- )- return []-- def get_issue_comments(- self, issue_number: int, comment_id: int | None = None- ) -> list[str] | None:- logger.warning('BitbucketDCIssueHandler.get_issue_comments not implemented')- return []-- def get_issue_thread_comments(self, issue_number: int) -> list[str]:- logger.warning(- 'BitbucketDCIssueHandler.get_issue_thread_comments not implemented'- )- return []-- def get_issue_review_comments(self, issue_number: int) -> list[str]:- logger.warning(- 'BitbucketDCIssueHandler.get_issue_review_comments not implemented'- )- return []-- def get_issue_review_threads(self, issue_number: int) -> list[ReviewThread]:- logger.warning(- 'BitbucketDCIssueHandler.get_issue_review_threads not implemented'- )- return []-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- # DC has no issue tracker; return closing_issues immediately without API calls- return closing_issues-- def request_reviewers(self, reviewer: str, pr_number: int) -> None:- logger.warning('BitbucketDCIssueHandler.request_reviewers not implemented')-- def get_issue_references(self, body: str) -> list[int]:- return extract_issue_references(body)-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- if not issue_numbers:- raise ValueError('Unspecified issue numbers')-- converted_issues = []- for issue_number in issue_numbers:- try:- issue = call_async_from_sync(- self.get_issue, GENERAL_TIMEOUT, issue_number- )- converted_issues.append(issue)- except Exception as e:- logger.warning(f'Failed to fetch pull request {issue_number}: {e}')-- return converted_issues---class BitbucketDCPRHandler(BitbucketDCIssueHandler):- """Handler for Bitbucket Data Center pull requests, extending the issue handler."""-- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'bitbucket.example.com',- ):- super().__init__(owner, repo, token, username, base_domain)diff --git a/openhands/resolver/interfaces/forgejo.py b/openhands/resolver/interfaces/forgejo.pydeleted file mode 100644index bb7ffa5478..0000000000--- a/openhands/resolver/interfaces/forgejo.py+++ /dev/null@@ -1,487 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from __future__ import annotations--from typing import Any-from urllib.parse import quote--import httpx--from openhands.core.logger import openhands_logger as logger-from openhands.resolver.interfaces.issue import (- Issue,- IssueHandlerInterface,- ReviewThread,-)-from openhands.resolver.utils import extract_issue_references---class ForgejoIssueHandler(IssueHandlerInterface):- """Issue handler implementation for Forgejo-based providers (e.g. Codeberg)."""-- API_PREFIX = '/api/v1'-- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'codeberg.org',- ):- self.owner = owner- self.repo = repo- self.token = token- self.username = username- self.base_domain = base_domain- self.base_url = self.get_base_url()- self.download_url = self.get_download_url()- self.clone_url = self.get_clone_url()- self.headers = self.get_headers()-- def _api_root(self) -> str:- return f'https://{self.base_domain}{self.API_PREFIX}'-- @staticmethod- def _to_int(value: Any) -> int:- try:- return int(value)- except (TypeError, ValueError):- return 0-- def set_owner(self, owner: str) -> None:- self.owner = owner- self.base_url = self.get_base_url()- self.download_url = self.get_download_url()-- def get_headers(self) -> dict[str, str]:- return {- 'Authorization': f'token {self.token}',- 'Accept': 'application/json',- }-- def get_base_url(self) -> str:- return f'{self._api_root()}/repos/{self.owner}/{self.repo}'-- def get_authorize_url(self) -> str:- credential = (- f'{self.username}:{self.token}'- if self.username- else f'x-auth-token:{self.token}'- )- return f'https://{credential}@{self.base_domain}/'-- def get_branch_url(self, branch_name: str) -> str:- escaped_branch = quote(branch_name, safe='')- return f'{self.get_base_url()}/branches/{escaped_branch}'-- def get_download_url(self) -> str:- return f'{self.get_base_url()}/issues'-- def get_clone_url(self) -> str:- credential = (- f'{self.username}:{self.token}'- if self.username- else f'x-access-token:{self.token}'- )- return f'https://{credential}@{self.base_domain}/{self.owner}/{self.repo}.git'-- def get_graphql_url(self) -> str:- # Forgejo does not expose a GraphQL endpoint.- return ''-- def get_compare_url(self, branch_name: str) -> str:- return (- f'https://{self.base_domain}/{self.owner}/{self.repo}/compare/{branch_name}'- )-- def download_issues(self) -> list[Any]:- page = 1- all_issues: list[Any] = []-- while True:- params = {'state': 'open', 'limit': '50', 'page': str(page)}- response = httpx.get(self.download_url, headers=self.headers, params=params)- response.raise_for_status()- issues = response.json()-- if not issues:- break-- if not isinstance(issues, list) or any(- not isinstance(issue, dict) for issue in issues- ):- raise ValueError(- 'Expected list of dictionaries from Forgejo issues API.'- )-- all_issues.extend(issues)- page += 1-- return all_issues-- def get_issue_comments(- self, issue_number: int, comment_id: int | None = None- ) -> list[str] | None:- url = f'{self.get_download_url()}/{issue_number}/comments'- page = 1- params = {'limit': '50', 'page': str(page)}- all_comments: list[str] = []-- while True:- response = httpx.get(url, headers=self.headers, params=params)- response.raise_for_status()- comments = response.json()-- if not comments:- break-- if comment_id is not None:- matching_comment = next(- (- comment['body']- for comment in comments- if self._to_int(comment.get('id')) == comment_id- ),- None,- )- if matching_comment:- return [matching_comment]- else:- all_comments.extend(- comment['body'] for comment in comments if comment.get('body')- )-- page += 1- params = {'limit': '50', 'page': str(page)}-- return all_comments if all_comments else None-- def get_pull_url(self, pr_number: int) -> str:- return f'https://{self.base_domain}/{self.owner}/{self.repo}/pulls/{pr_number}'-- def get_branch_name(self, base_branch_name: str) -> str:- branch_name = base_branch_name- attempt = 1- while self.branch_exists(branch_name):- attempt += 1- branch_name = f'{base_branch_name}-try{attempt}'- return branch_name-- def get_default_branch_name(self) -> str:- response = httpx.get(self.get_base_url(), headers=self.headers)- response.raise_for_status()- data = response.json()- return str(data.get('default_branch'))-- def branch_exists(self, branch_name: str) -> bool:- response = httpx.get(self.get_branch_url(branch_name), headers=self.headers)- exists = response.status_code == 200- logger.info(f'Branch {branch_name} exists: {exists}')- return exists-- def reply_to_comment(self, pr_number: int, comment_id: str, reply: str) -> None:- # Forgejo does not support threaded replies via API; add a regular comment referencing the original ID.- message = f'OpenHands reply to comment {comment_id}\n\n{reply}'- self.send_comment_msg(pr_number, message)-- def create_pull_request(self, data: dict[str, Any] | None = None) -> dict[str, Any]:- payload = data or {}- response = httpx.post(- f'{self.get_base_url()}/pulls', headers=self.headers, json=payload- )- if response.status_code == 403:- raise RuntimeError(- 'Failed to create pull request due to missing permissions. '- 'Ensure the token has write access to the repository.'- )- response.raise_for_status()- pr_data = response.json()- pr_data.setdefault('number', pr_data.get('index'))- if 'html_url' not in pr_data and 'url' in pr_data:- pr_data['html_url'] = pr_data['url']- return dict(pr_data)-- def request_reviewers(self, reviewer: str, pr_number: int) -> None:- url = f'{self.get_base_url()}/pulls/{pr_number}/requested_reviewers'- response = httpx.post(- url,- headers=self.headers,- json={'reviewers': [reviewer]},- )- if response.status_code not in (200, 201, 204):- logger.warning(- f'Failed to request review from {reviewer}: {response.status_code} {response.text}'- )-- def send_comment_msg(self, issue_number: int, msg: str) -> None:- comment_url = f'{self.get_download_url()}/{issue_number}/comments'- response = httpx.post(- comment_url,- headers=self.headers,- json={'body': msg},- )- if response.status_code not in (200, 201):- logger.error(- f'Failed to post comment: {response.status_code} {response.text}'- )-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- new_references: list[int] = []-- if issue_body:- new_references.extend(extract_issue_references(issue_body))-- if review_comments:- for comment in review_comments:- new_references.extend(extract_issue_references(comment))-- if review_threads:- for thread in review_threads:- new_references.extend(extract_issue_references(thread.comment))-- if thread_comments:- for thread_comment in thread_comments:- new_references.extend(extract_issue_references(thread_comment))-- unique_ids = set(new_references).difference(closing_issue_numbers)-- for issue_number in unique_ids:- try:- response = httpx.get(- f'{self.get_download_url()}/{issue_number}',- headers=self.headers,- )- response.raise_for_status()- issue_data = response.json()- body = issue_data.get('body', '')- if body:- closing_issues.append(body)- except httpx.HTTPError as exc:- logger.warning(f'Failed to fetch issue {issue_number}: {exc}')-- return closing_issues-- def get_pull_url_for_issue(self, issue_number: int) -> str:- return (- f'https://{self.base_domain}/{self.owner}/{self.repo}/issues/{issue_number}'- )-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- if not issue_numbers:- raise ValueError('Unspecified issue numbers')-- all_issues = self.download_issues()- logger.info(f'Limiting resolving to issues {issue_numbers}.')- filtered = [- issue- for issue in all_issues- if self._to_int(issue.get('number') or issue.get('index')) in issue_numbers- ]-- converted: list[Issue] = []- for issue in filtered:- if any(issue.get(key) is None for key in ['number', 'title']):- logger.warning(- f'Skipping issue {issue} as it is missing number or title.'- )- continue-- issue_number = self._to_int(issue.get('number') or issue.get('index'))- body = issue.get('body') or ''- thread_comments = self.get_issue_comments(issue_number, comment_id)-- issue_details = Issue(- owner=self.owner,- repo=self.repo,- number=issue_number,- title=issue['title'],- body=body,- thread_comments=thread_comments,- review_comments=None,- review_threads=None,- )- converted.append(issue_details)-- return converted---class ForgejoPRHandler(ForgejoIssueHandler):- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'codeberg.org',- ):- super().__init__(owner, repo, token, username, base_domain)- self.download_url = f'{self.get_base_url()}/pulls'-- def download_pr_metadata(- self, pull_number: int, comment_id: int | None = None- ) -> tuple[list[str], list[int], list[str] | None, list[ReviewThread], list[str]]:- closing_issues: list[str] = []- closing_issue_numbers: list[int] = []-- try:- response = httpx.get(- f'{self.get_base_url()}/pulls/{pull_number}', headers=self.headers- )- response.raise_for_status()- pr_data = response.json()- body = pr_data.get('body') or ''- closing_refs = extract_issue_references(body)- closing_issue_numbers.extend(closing_refs)- if body:- closing_issues.append(body)- except httpx.HTTPError as exc:- logger.warning(f'Failed to fetch PR metadata for {pull_number}: {exc}')-- review_comments = self.get_pr_comments(pull_number, comment_id)- review_threads: list[ReviewThread] = []- thread_ids: list[str] = []-- return (- closing_issues,- closing_issue_numbers,- review_comments,- review_threads,- thread_ids,- )-- def get_pr_comments(- self, pr_number: int, comment_id: int | None = None- ) -> list[str] | None:- url = f'{self.get_base_url()}/pulls/{pr_number}/comments'- page = 1- params = {'limit': '50', 'page': str(page)}- collected: list[str] = []-- while True:- response = httpx.get(url, headers=self.headers, params=params)- response.raise_for_status()- comments = response.json()-- if not comments:- break-- filtered = [- comment for comment in comments if not comment.get('is_system', False)- ]-- if comment_id is not None:- matching = next(- (- comment['body']- for comment in filtered- if self._to_int(comment.get('id')) == comment_id- ),- None,- )- if matching:- return [matching]- else:- collected.extend(- comment['body'] for comment in filtered if comment.get('body')- )-- page += 1- params = {'limit': '50', 'page': str(page)}-- return collected if collected else None-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- return super().get_context_from_external_issues_references(- closing_issues,- closing_issue_numbers,- issue_body,- review_comments,- review_threads,- thread_comments,- )-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- if not issue_numbers:- raise ValueError('Unspecified issue numbers')-- response = httpx.get(self.download_url, headers=self.headers)- response.raise_for_status()- all_prs = response.json()-- logger.info(f'Limiting resolving to PRs {issue_numbers}.')- filtered = [- pr- for pr in all_prs- if self._to_int(pr.get('number') or pr.get('index')) in issue_numbers- ]-- converted: list[Issue] = []- for pr in filtered:- if any(pr.get(key) is None for key in ['number', 'title']):- logger.warning(f'Skipping PR {pr} as it is missing number or title.')- continue-- body = pr.get('body') or ''- pr_number = self._to_int(pr.get('number') or pr.get('index', 0))- (- closing_issues,- closing_issue_numbers,- review_comments,- review_threads,- thread_ids,- ) = self.download_pr_metadata(pr_number, comment_id)- head_branch = (pr.get('head') or {}).get('ref')- thread_comments = self.get_pr_comments(pr_number, comment_id)-- closing_issues = self.get_context_from_external_issues_references(- closing_issues,- closing_issue_numbers,- body,- review_comments,- review_threads,- thread_comments,- )-- issue_details = Issue(- owner=self.owner,- repo=self.repo,- number=pr_number,- title=pr['title'],- body=body,- closing_issues=closing_issues,- review_comments=review_comments,- review_threads=review_threads,- thread_ids=thread_ids,- head_branch=head_branch,- thread_comments=thread_comments,- )-- converted.append(issue_details)-- return converteddiff --git a/openhands/resolver/interfaces/github.py b/openhands/resolver/interfaces/github.pydeleted file mode 100644index 7e62c7dc27..0000000000--- a/openhands/resolver/interfaces/github.py+++ /dev/null@@ -1,644 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from typing import Any--import httpx--from openhands.core.logger import openhands_logger as logger-from openhands.resolver.interfaces.issue import (- Issue,- IssueHandlerInterface,- ReviewThread,-)-from openhands.resolver.utils import extract_issue_references---class GithubIssueHandler(IssueHandlerInterface):- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'github.com',- ):- """Initialize a GitHub issue handler.-- Args:- owner: The owner of the repository- repo: The name of the repository- token: The GitHub personal access token- username: Optional GitHub username- base_domain: The domain for GitHub Enterprise (default: "github.com")- """- self.owner = owner- self.repo = repo- self.token = token- self.username = username- self.base_domain = base_domain- self.base_url = self.get_base_url()- self.download_url = self.get_download_url()- self.clone_url = self.get_clone_url()- self.headers = self.get_headers()-- def set_owner(self, owner: str) -> None:- self.owner = owner-- def get_headers(self) -> dict[str, str]:- return {- 'Authorization': f'token {self.token}',- 'Accept': 'application/vnd.github.v3+json',- }-- def get_base_url(self) -> str:- if self.base_domain == 'github.com':- return f'https://api.github.com/repos/{self.owner}/{self.repo}'- else:- return f'https://{self.base_domain}/api/v3/repos/{self.owner}/{self.repo}'-- def get_authorize_url(self) -> str:- return f'https://{self.username}:{self.token}@{self.base_domain}/'-- def get_branch_url(self, branch_name: str) -> str:- return self.get_base_url() + f'/branches/{branch_name}'-- def get_download_url(self) -> str:- return f'{self.base_url}/issues'-- def get_clone_url(self) -> str:- username_and_token = (- f'{self.username}:{self.token}'- if self.username- else f'x-auth-token:{self.token}'- )- return f'https://{username_and_token}@{self.base_domain}/{self.owner}/{self.repo}.git'-- def get_graphql_url(self) -> str:- if self.base_domain == 'github.com':- return 'https://api.github.com/graphql'- else:- return f'https://{self.base_domain}/api/graphql'-- def get_compare_url(self, branch_name: str) -> str:- return f'https://{self.base_domain}/{self.owner}/{self.repo}/compare/{branch_name}?expand=1'-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- """Download issues from Github.-- Args:- issue_numbers: The numbers of the issues to download- comment_id: The ID of a single comment, if provided, otherwise all comments-- Returns:- List of Github issues.- """- if not issue_numbers:- raise ValueError('Unspecified issue number')-- all_issues = self.download_issues()- logger.info(f'Limiting resolving to issues {issue_numbers}.')- all_issues = [- issue- for issue in all_issues- if issue['number'] in issue_numbers and 'pull_request' not in issue- ]-- if len(issue_numbers) == 1 and not all_issues:- raise ValueError(f'Issue {issue_numbers[0]} not found')-- converted_issues = []- for issue in all_issues:- # Check for required fields (number and title)- if any([issue.get(key) is None for key in ['number', 'title']]):- logger.warning(- f'Skipping issue {issue} as it is missing number or title.'- )- continue-- # Handle empty body by using empty string- if issue.get('body') is None:- issue['body'] = ''-- # Get issue thread comments- thread_comments = self.get_issue_comments(- issue['number'], comment_id=comment_id- )- # Convert empty lists to None for optional fields- issue_details = Issue(- owner=self.owner,- repo=self.repo,- number=issue['number'],- title=issue['title'],- body=issue['body'],- thread_comments=thread_comments,- review_comments=None, # Initialize review comments as None for regular issues- )-- converted_issues.append(issue_details)-- return converted_issues-- def download_issues(self) -> list[Any]:- params: dict[str, int | str] = {'state': 'open', 'per_page': 100, 'page': 1}- all_issues = []-- while True:- response = httpx.get(self.download_url, headers=self.headers, params=params)- response.raise_for_status()- issues = response.json()-- if not issues:- break-- if not isinstance(issues, list) or any(- [not isinstance(issue, dict) for issue in issues]- ):- raise ValueError(- 'Expected list of dictionaries from Service Github API.'- )-- all_issues.extend(issues)- assert isinstance(params['page'], int)- params['page'] += 1-- return all_issues-- def get_issue_comments(- self, issue_number: int, comment_id: int | None = None- ) -> list[str] | None:- """Download comments for a specific issue from Github."""- url = f'{self.download_url}/{issue_number}/comments'- params = {'per_page': 100, 'page': 1}- all_comments = []-- while True:- response = httpx.get(url, headers=self.headers, params=params)- response.raise_for_status()- comments = response.json()-- if not comments:- break-- if comment_id:- matching_comment = next(- (- comment['body']- for comment in comments- if comment['id'] == comment_id- ),- None,- )- if matching_comment:- return [matching_comment]- else:- all_comments.extend([comment['body'] for comment in comments])-- params['page'] += 1-- return all_comments if all_comments else None-- def branch_exists(self, branch_name: str) -> bool:- logger.info(f'Checking if branch {branch_name} exists...')- response = httpx.get(- f'{self.base_url}/branches/{branch_name}', headers=self.headers- )- exists = response.status_code == 200- logger.info(f'Branch {branch_name} exists: {exists}')- return exists-- def get_branch_name(self, base_branch_name: str) -> str:- branch_name = base_branch_name- attempt = 1- while self.branch_exists(branch_name):- attempt += 1- branch_name = f'{base_branch_name}-try{attempt}'- return branch_name-- def reply_to_comment(self, pr_number: int, comment_id: str, reply: str) -> None:- # Opting for graphql as REST API doesn't allow reply to replies in comment threads- query = """- mutation($body: String!, $pullRequestReviewThreadId: ID!) {- addPullRequestReviewThreadReply(input: { body: $body, pullRequestReviewThreadId: $pullRequestReviewThreadId }) {- comment {- id- body- createdAt- }- }- }- """-- comment_reply = f'Openhands fix success summary\n\n\n{reply}'- variables = {'body': comment_reply, 'pullRequestReviewThreadId': comment_id}- url = self.get_graphql_url()- headers = {- 'Authorization': f'Bearer {self.token}',- 'Content-Type': 'application/json',- }-- response = httpx.post(- url, json={'query': query, 'variables': variables}, headers=headers- )- response.raise_for_status()-- def get_pull_url(self, pr_number: int) -> str:- return f'https://{self.base_domain}/{self.owner}/{self.repo}/pull/{pr_number}'-- def get_default_branch_name(self) -> str:- response = httpx.get(f'{self.base_url}', headers=self.headers)- response.raise_for_status()- data = response.json()- return str(data['default_branch'])-- def create_pull_request(self, data: dict[str, Any] | None = None) -> dict[str, Any]:- if data is None:- data = {}- response = httpx.post(f'{self.base_url}/pulls', headers=self.headers, json=data)- if response.status_code == 403:- raise RuntimeError(- 'Failed to create pull request due to missing permissions. '- 'Make sure that the provided token has push permissions for the repository.'- )- response.raise_for_status()- pr_data = response.json()- return dict(pr_data)-- def request_reviewers(self, reviewer: str, pr_number: int) -> None:- review_data = {'reviewers': [reviewer]}- review_response = httpx.post(- f'{self.base_url}/pulls/{pr_number}/requested_reviewers',- headers=self.headers,- json=review_data,- )- if review_response.status_code != 201:- logger.warning(- f'Failed to request review from {reviewer}: {review_response.text}'- )-- def send_comment_msg(self, issue_number: int, msg: str) -> None:- """Send a comment message to a GitHub issue or pull request.-- Args:- issue_number: The issue or pull request number- msg: The message content to post as a comment- """- # Post a comment on the PR- comment_url = f'{self.base_url}/issues/{issue_number}/comments'- comment_data = {'body': msg}- comment_response = httpx.post(- comment_url, headers=self.headers, json=comment_data- )- if comment_response.status_code != 201:- logger.error(- f'Failed to post comment: {comment_response.status_code} {comment_response.text}'- )- else:- logger.info(f'Comment added to the PR: {msg}')-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- return []---class GithubPRHandler(GithubIssueHandler):- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'github.com',- ):- """Initialize a GitHub PR handler.-- Args:- owner: The owner of the repository- repo: The name of the repository- token: The GitHub personal access token- username: Optional GitHub username- base_domain: The domain for GitHub Enterprise (default: "github.com")- """- super().__init__(owner, repo, token, username, base_domain)- if self.base_domain == 'github.com':- self.download_url = (- f'https://api.github.com/repos/{self.owner}/{self.repo}/pulls'- )- else:- self.download_url = f'https://{self.base_domain}/api/v3/repos/{self.owner}/{self.repo}/pulls'-- def download_pr_metadata(- self, pull_number: int, comment_id: int | None = None- ) -> tuple[list[str], list[int], list[str], list[ReviewThread], list[str]]:- """Run a GraphQL query against the GitHub API for information.-- Retrieves information about:- 1. unresolved review comments- 2. referenced issues the pull request would close-- Args:- pull_number: The number of the pull request to query.- comment_id: Optional ID of a specific comment to focus on.- query: The GraphQL query as a string.- variables: A dictionary of variables for the query.- token: Your GitHub personal access token.-- Returns:- The JSON response from the GitHub API.- """- # Using graphql as REST API doesn't indicate resolved status for review comments- # TODO: grabbing the first 10 issues, 100 review threads, and 100 coments; add pagination to retrieve all- query = """- query($owner: String!, $repo: String!, $pr: Int!) {- repository(owner: $owner, name: $repo) {- pullRequest(number: $pr) {- closingIssuesReferences(first: 10) {- edges {- node {- body- number- }- }- }- url- reviews(first: 100) {- nodes {- body- state- fullDatabaseId- }- }- reviewThreads(first: 100) {- edges{- node{- id- isResolved- comments(first: 100) {- totalCount- nodes {- body- path- fullDatabaseId- }- }- }- }- }- }- }- }- """-- variables = {'owner': self.owner, 'repo': self.repo, 'pr': pull_number}-- url = self.get_graphql_url()- headers = {- 'Authorization': f'Bearer {self.token}',- 'Content-Type': 'application/json',- }-- response = httpx.post(- url, json={'query': query, 'variables': variables}, headers=headers- )- response.raise_for_status()- response_json = response.json()-- # Parse the response to get closing issue references and unresolved review comments- pr_data = (- response_json.get('data', {}).get('repository', {}).get('pullRequest', {})- )-- # Get closing issues- closing_issues = pr_data.get('closingIssuesReferences', {}).get('edges', [])- closing_issues_bodies = [issue['node']['body'] for issue in closing_issues]- closing_issue_numbers = [- issue['node']['number'] for issue in closing_issues- ] # Extract issue numbers-- # Get review comments- reviews = pr_data.get('reviews', {}).get('nodes', [])- if comment_id is not None:- reviews = [- review- for review in reviews- if int(review['fullDatabaseId']) == comment_id- ]- review_bodies = [review['body'] for review in reviews]-- # Get unresolved review threads- review_threads = []- thread_ids = [] # Store thread IDs; agent replies to the thread- raw_review_threads = pr_data.get('reviewThreads', {}).get('edges', [])- for thread in raw_review_threads:- node = thread.get('node', {})- if not node.get(- 'isResolved', True- ): # Check if the review thread is unresolved- id = node.get('id')- thread_contains_comment_id = False- my_review_threads = node.get('comments', {}).get('nodes', [])- message = ''- files = []- for i, review_thread in enumerate(my_review_threads):- if (- comment_id is not None- and int(review_thread['fullDatabaseId']) == comment_id- ):- thread_contains_comment_id = True-- if (- i == len(my_review_threads) - 1- ): # Check if it's the last thread in the thread- if len(my_review_threads) > 1:- message += '---\n' # Add "---" before the last message if there's more than one thread- message += 'latest feedback:\n' + review_thread['body'] + '\n'- else:- message += (- review_thread['body'] + '\n'- ) # Add each thread in a new line-- file = review_thread.get('path')- if file and file not in files:- files.append(file)-- if comment_id is None or thread_contains_comment_id:- unresolved_thread = ReviewThread(comment=message, files=files)- review_threads.append(unresolved_thread)- thread_ids.append(id)-- return (- closing_issues_bodies,- closing_issue_numbers,- review_bodies,- review_threads,- thread_ids,- )-- # Override processing of downloaded issues- def get_pr_comments(- self, pr_number: int, comment_id: int | None = None- ) -> list[str] | None:- """Download comments for a specific pull request from Github."""- if self.base_domain == 'github.com':- url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{pr_number}/comments'- else:- url = f'https://{self.base_domain}/api/v3/repos/{self.owner}/{self.repo}/issues/{pr_number}/comments'- headers = {- 'Authorization': f'token {self.token}',- 'Accept': 'application/vnd.github.v3+json',- }- params = {'per_page': 100, 'page': 1}- all_comments = []-- while True:- response = httpx.get(url, headers=headers, params=params)- response.raise_for_status()- comments = response.json()-- if not comments:- break-- if comment_id is not None:- matching_comment = next(- (- comment['body']- for comment in comments- if comment['id'] == comment_id- ),- None,- )- if matching_comment:- return [matching_comment]- else:- all_comments.extend([comment['body'] for comment in comments])-- params['page'] += 1-- return all_comments if all_comments else None-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- new_issue_references = []-- if issue_body:- new_issue_references.extend(extract_issue_references(issue_body))-- if review_comments:- for comment in review_comments:- new_issue_references.extend(extract_issue_references(comment))-- if review_threads:- for review_thread in review_threads:- new_issue_references.extend(- extract_issue_references(review_thread.comment)- )-- if thread_comments:- for thread_comment in thread_comments:- new_issue_references.extend(extract_issue_references(thread_comment))-- non_duplicate_references = set(new_issue_references)- unique_issue_references = non_duplicate_references.difference(- closing_issue_numbers- )-- for issue_number in unique_issue_references:- try:- if self.base_domain == 'github.com':- url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{issue_number}'- else:- url = f'https://{self.base_domain}/api/v3/repos/{self.owner}/{self.repo}/issues/{issue_number}'- headers = {- 'Authorization': f'Bearer {self.token}',- 'Accept': 'application/vnd.github.v3+json',- }- response = httpx.get(url, headers=headers)- response.raise_for_status()- issue_data = response.json()- issue_body = issue_data.get('body', '')- if issue_body:- closing_issues.append(issue_body)- except httpx.HTTPError as e:- logger.warning(f'Failed to fetch issue {issue_number}: {str(e)}')-- return closing_issues-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- if not issue_numbers:- raise ValueError('Unspecified issue numbers')-- all_issues = self.download_issues()- logger.info(f'Limiting resolving to issues {issue_numbers}.')- all_issues = [issue for issue in all_issues if issue['number'] in issue_numbers]-- converted_issues = []- for issue in all_issues:- # For PRs, body can be None- if any([issue.get(key) is None for key in ['number', 'title']]):- logger.warning(f'Skipping #{issue} as it is missing number or title.')- continue-- # Handle None body for PRs- body = issue.get('body') if issue.get('body') is not None else ''- (- closing_issues,- closing_issues_numbers,- review_comments,- review_threads,- thread_ids,- ) = self.download_pr_metadata(issue['number'], comment_id=comment_id)- head_branch = issue['head']['ref']-- # Get PR thread comments- thread_comments = self.get_pr_comments(- issue['number'], comment_id=comment_id- )-- closing_issues = self.get_context_from_external_issues_references(- closing_issues,- closing_issues_numbers,- body,- review_comments,- review_threads,- thread_comments,- )-- issue_details = Issue(- owner=self.owner,- repo=self.repo,- number=issue['number'],- title=issue['title'],- body=body,- closing_issues=closing_issues,- review_comments=review_comments,- review_threads=review_threads,- thread_ids=thread_ids,- head_branch=head_branch,- thread_comments=thread_comments,- )-- converted_issues.append(issue_details)-- return converted_issuesdiff --git a/openhands/resolver/interfaces/gitlab.py b/openhands/resolver/interfaces/gitlab.pydeleted file mode 100644index e8a0ec2ee9..0000000000--- a/openhands/resolver/interfaces/gitlab.py+++ /dev/null@@ -1,617 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from typing import Any-from urllib.parse import quote--import httpx--from openhands.core.logger import openhands_logger as logger-from openhands.resolver.interfaces.issue import (- Issue,- IssueHandlerInterface,- ReviewThread,-)-from openhands.resolver.utils import extract_issue_references---class GitlabIssueHandler(IssueHandlerInterface):- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'gitlab.com',- ):- """Initialize a GitLab issue handler.-- Args:- owner: The owner of the repository- repo: The name of the repository- token: The GitLab personal access token- username: Optional GitLab username- base_domain: The domain for GitLab Enterprise (default: "gitlab.com")- """- self.owner = owner- self.repo = repo- self.token = token- self.username = username- self.base_domain = base_domain- self.base_url = self.get_base_url()- self.download_url = self.get_download_url()- self.clone_url = self.get_clone_url()- self.headers = self.get_headers()-- def set_owner(self, owner: str) -> None:- self.owner = owner-- def get_headers(self) -> dict[str, str]:- return {- 'Authorization': f'Bearer {self.token}',- 'Accept': 'application/json',- }-- def get_base_url(self) -> str:- project_path = quote(f'{self.owner}/{self.repo}', safe='')- return f'https://{self.base_domain}/api/v4/projects/{project_path}'-- def get_authorize_url(self) -> str:- return f'https://{self.username}:{self.token}@{self.base_domain}/'-- def get_branch_url(self, branch_name: str) -> str:- return self.get_base_url() + f'/repository/branches/{branch_name}'-- def get_download_url(self) -> str:- return f'{self.base_url}/issues'-- def get_clone_url(self) -> str:- username_and_token = self.token- if self.username:- username_and_token = f'{self.username}:{self.token}'- return f'https://{username_and_token}@{self.base_domain}/{self.owner}/{self.repo}.git'-- def get_graphql_url(self) -> str:- return f'https://{self.base_domain}/api/graphql'-- def get_compare_url(self, branch_name: str) -> str:- return f'https://{self.base_domain}/{self.owner}/{self.repo}/-/compare/{self.get_default_branch_name()}...{branch_name}'-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- """Download issues from Gitlab.-- Args:- issue_numbers: The numbers of the issues to download- comment_id: The ID of a single comment, if provided, otherwise all comments-- Returns:- List of Gitlab issues.- """- if not issue_numbers:- raise ValueError('Unspecified issue number')-- all_issues = self.download_issues()- logger.info(f'Limiting resolving to issues {issue_numbers}.')- all_issues = [- issue- for issue in all_issues- # if issue['iid'] in issue_numbers and issue['merge_requests_count'] == 0- if issue['iid'] in issue_numbers # TODO for testing- ]-- if len(issue_numbers) == 1 and not all_issues:- raise ValueError(f'Issue {issue_numbers[0]} not found')-- converted_issues = []- for issue in all_issues:- if any([issue.get(key) is None for key in ['iid', 'title']]):- logger.warning(f'Skipping issue {issue} as it is missing iid or title.')- continue-- # Handle empty body by using empty string- if issue.get('description') is None:- issue['description'] = ''-- # Get issue thread comments- thread_comments = self.get_issue_comments(- issue['iid'], comment_id=comment_id- )- # Convert empty lists to None for optional fields- issue_details = Issue(- owner=self.owner,- repo=self.repo,- number=issue['iid'],- title=issue['title'],- body=issue['description'],- thread_comments=thread_comments,- review_comments=None, # Initialize review comments as None for regular issues- )-- converted_issues.append(issue_details)-- return converted_issues-- def download_issues(self) -> list[Any]:- params: dict[str, int | str] = {- 'state': 'opened',- 'scope': 'all',- 'per_page': 100,- 'page': 1,- }- all_issues = []-- while True:- response = httpx.get(self.download_url, headers=self.headers, params=params)- response.raise_for_status()- issues = response.json()-- if not issues:- break-- if not isinstance(issues, list) or any(- [not isinstance(issue, dict) for issue in issues]- ):- raise ValueError(- 'Expected list of dictionaries from Service Gitlab API.'- )-- all_issues.extend(issues)- assert isinstance(params['page'], int)- params['page'] += 1-- return all_issues-- def get_issue_comments(- self, issue_number: int, comment_id: int | None = None- ) -> list[str] | None:- """Download comments for a specific issue from Gitlab."""- url = f'{self.download_url}/{issue_number}/notes'- params = {'per_page': 100, 'page': 1}- all_comments = []-- while True:- response = httpx.get(url, headers=self.headers, params=params)- response.raise_for_status()- comments = response.json()-- if not comments:- break-- if comment_id:- matching_comment = next(- (- comment['body']- for comment in comments- if comment['id'] == comment_id- ),- None,- )- if matching_comment:- return [matching_comment]- else:- all_comments.extend([comment['body'] for comment in comments])-- params['page'] += 1-- return all_comments if all_comments else None-- def branch_exists(self, branch_name: str) -> bool:- logger.info(f'Checking if branch {branch_name} exists...')- response = httpx.get(- f'{self.base_url}/repository/branches/{branch_name}', headers=self.headers- )- exists = response.status_code == 200- logger.info(f'Branch {branch_name} exists: {exists}')- return exists-- def get_branch_name(self, base_branch_name: str) -> str:- branch_name = base_branch_name- attempt = 1- while self.branch_exists(branch_name):- attempt += 1- branch_name = f'{base_branch_name}-try{attempt}'- return branch_name-- def reply_to_comment(self, pr_number: int, comment_id: str, reply: str) -> None:- response = httpx.get(- f'{self.base_url}/merge_requests/{pr_number}/discussions/{comment_id.split("/")[-1]}',- headers=self.headers,- )- response.raise_for_status()- discussions = response.json()- if len(discussions.get('notes', [])) > 0:- data = {- 'body': f'Openhands fix success summary\n\n\n{reply}',- 'note_id': discussions.get('notes', [])[-1]['id'],- }- response = httpx.post(- f'{self.base_url}/merge_requests/{pr_number}/discussions/{comment_id.split("/")[-1]}/notes',- headers=self.headers,- json=data,- )- response.raise_for_status()-- def get_pull_url(self, pr_number: int) -> str:- return f'https://{self.base_domain}/{self.owner}/{self.repo}/-/merge_requests/{pr_number}'-- def get_default_branch_name(self) -> str:- response = httpx.get(f'{self.base_url}', headers=self.headers)- response.raise_for_status()- data = response.json()- return str(data['default_branch'])-- def create_pull_request(self, data: dict[str, Any] | None = None) -> dict[str, Any]:- if data is None:- data = {}- response = httpx.post(- f'{self.base_url}/merge_requests', headers=self.headers, json=data- )- if response.status_code == 403:- raise RuntimeError(- 'Failed to create pull request due to missing permissions. '- 'Make sure that the provided token has push permissions for the repository.'- )- response.raise_for_status()- pr_data = response.json()- if 'web_url' in pr_data:- pr_data['html_url'] = pr_data['web_url']-- if 'iid' in pr_data:- pr_data['number'] = pr_data['iid']-- return dict(pr_data)-- def request_reviewers(self, reviewer: str, pr_number: int) -> None:- response = httpx.get(- f'https://{self.base_domain}/api/v4/users?username={reviewer}',- headers=self.headers,- )- response.raise_for_status()- user_data = response.json()- if len(user_data) > 0:- review_data = {'reviewer_ids': [user_data[0]['id']]}- review_response = httpx.put(- f'{self.base_url}/merge_requests/{pr_number}',- headers=self.headers,- json=review_data,- )- if review_response.status_code != 200:- logger.warning(- f'Failed to request review from {reviewer}: {review_response.text}'- )-- def send_comment_msg(self, issue_number: int, msg: str) -> None:- """Send a comment message to a GitHub issue or pull request.-- Args:- issue_number: The issue or pull request number- msg: The message content to post as a comment- """- # Post a comment on the PR- comment_url = f'{self.base_url}/issues/{issue_number}/notes'- comment_data = {'body': msg}- comment_response = httpx.post(- comment_url, headers=self.headers, json=comment_data- )- if comment_response.status_code != 201:- logger.error(- f'Failed to post comment: {comment_response.status_code} {comment_response.text}'- )- else:- logger.info(f'Comment added to the PR: {msg}')-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- return []---class GitlabPRHandler(GitlabIssueHandler):- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str | None = None,- base_domain: str = 'gitlab.com',- ):- """Initialize a GitLab PR handler.-- Args:- owner: The owner of the repository- repo: The name of the repository- token: The GitLab personal access token- username: Optional GitLab username- base_domain: The domain for GitLab Enterprise (default: "gitlab.com")- """- super().__init__(owner, repo, token, username, base_domain)- self.download_url = f'{self.base_url}/merge_requests'-- def download_pr_metadata(- self, pull_number: int, comment_id: int | None = None- ) -> tuple[list[str], list[int], list[str] | None, list[ReviewThread], list[str]]:- """Run a GraphQL query against the Gitlab API for information.-- Retrieves information about:- 1. unresolved review comments- 2. referenced issues the pull request would close-- Args:- pull_number: The number of the pull request to query.- comment_id: Optional ID of a specific comment to focus on.- query: The GraphQL query as a string.- variables: A dictionary of variables for the query.- token: Your Gitlab personal access token.-- Returns:- The JSON response from the Gitlab API.- """- # Using graphql as REST API doesn't indicate resolved status for review comments- # TODO: grabbing the first 10 issues, 100 review threads, and 100 coments; add pagination to retrieve all- response = httpx.get(- f'{self.base_url}/merge_requests/{pull_number}/related_issues',- headers=self.headers,- )- response.raise_for_status()- closing_issues = response.json()- closing_issues_bodies = [issue['description'] for issue in closing_issues]- closing_issue_numbers = [- issue['iid'] for issue in closing_issues- ] # Extract issue numbers-- query = """- query($projectPath: ID!, $pr: String!) {- project(fullPath: $projectPath) {- mergeRequest(iid: $pr) {- webUrl- discussions(first: 100) {- edges {- node {- id- resolved- resolvable- notes(first: 100) {- nodes {- body- id- position {- filePath- }- }- }- }- }- }- }- }- }- """-- project_path = f'{self.owner}/{self.repo}'- variables = {'projectPath': project_path, 'pr': str(pull_number)}-- response = httpx.post(- self.get_graphql_url(),- json={'query': query, 'variables': variables},- headers=self.headers,- )- response.raise_for_status()- response_json = response.json()-- # Parse the response to get closing issue references and unresolved review comments- pr_data = (- response_json.get('data', {}).get('project', {}).get('mergeRequest', {})- )-- # Get review comments- review_bodies = None-- # Get unresolved review threads- review_threads = []- thread_ids = [] # Store thread IDs; agent replies to the thread- raw_review_threads = pr_data.get('discussions', {}).get('edges', [])-- for thread in raw_review_threads:- node = thread.get('node', {})- if not node.get('resolved', True) and node.get(- 'resolvable', True- ): # Check if the review thread is unresolved- id = node.get('id')- thread_contains_comment_id = False- my_review_threads = node.get('notes', {}).get('nodes', [])- message = ''- files = []- for i, review_thread in enumerate(my_review_threads):- if (- comment_id is not None- and int(review_thread['id'].split('/')[-1]) == comment_id- ):- thread_contains_comment_id = True-- if (- i == len(my_review_threads) - 1- ): # Check if it's the last thread in the thread- if len(my_review_threads) > 1:- message += '---\n' # Add "---" before the last message if there's more than one thread- message += 'latest feedback:\n' + review_thread['body'] + '\n'- else:- message += (- review_thread['body'] + '\n'- ) # Add each thread in a new line-- file = review_thread.get('position', {})- file = file.get('filePath') if file is not None else None- if file and file not in files:- files.append(file)-- if comment_id is None or thread_contains_comment_id:- unresolved_thread = ReviewThread(comment=message, files=files)- review_threads.append(unresolved_thread)- thread_ids.append(id)-- return (- closing_issues_bodies,- closing_issue_numbers,- review_bodies,- review_threads,- thread_ids,- )-- # Override processing of downloaded issues- def get_pr_comments(- self, pr_number: int, comment_id: int | None = None- ) -> list[str] | None:- """Download comments for a specific pull request from Gitlab."""- url = f'{self.base_url}/merge_requests/{pr_number}/notes'- params = {'per_page': 100, 'page': 1}- all_comments = []-- while True:- response = httpx.get(url, headers=self.headers, params=params)- response.raise_for_status()- comments = response.json()- comments = [- comment- for comment in comments- if comment.get('resolvable', True) and not comment.get('system', True)- ]-- if not comments:- break-- if comment_id is not None:- matching_comment = next(- (- comment['body']- for comment in comments- if comment['id'] == comment_id- ),- None,- )- if matching_comment:- return [matching_comment]- else:- all_comments.extend([comment['body'] for comment in comments])-- params['page'] += 1-- return all_comments if all_comments else None-- def get_context_from_external_issues_references(- self,- closing_issues: list[str],- closing_issue_numbers: list[int],- issue_body: str,- review_comments: list[str] | None,- review_threads: list[ReviewThread],- thread_comments: list[str] | None,- ) -> list[str]:- new_issue_references = []-- if issue_body:- new_issue_references.extend(extract_issue_references(issue_body))-- if review_comments:- for comment in review_comments:- new_issue_references.extend(extract_issue_references(comment))-- if review_threads:- for review_thread in review_threads:- new_issue_references.extend(- extract_issue_references(review_thread.comment)- )-- if thread_comments:- for thread_comment in thread_comments:- new_issue_references.extend(extract_issue_references(thread_comment))-- non_duplicate_references = set(new_issue_references)- unique_issue_references = non_duplicate_references.difference(- closing_issue_numbers- )-- for issue_number in unique_issue_references:- try:- url = f'{self.base_url}/issues/{issue_number}'- response = httpx.get(url, headers=self.headers)- response.raise_for_status()- issue_data = response.json()- issue_body = issue_data.get('description', '')- if issue_body:- closing_issues.append(issue_body)- except httpx.HTTPError as e:- logger.warning(f'Failed to fetch issue {issue_number}: {str(e)}')-- return closing_issues-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- if not issue_numbers:- raise ValueError('Unspecified issue numbers')-- all_issues = self.download_issues()- logger.info(f'Limiting resolving to issues {issue_numbers}.')- all_issues = [issue for issue in all_issues if issue['iid'] in issue_numbers]-- converted_issues = []- for issue in all_issues:- # For PRs, body can be None- if any([issue.get(key) is None for key in ['iid', 'title']]):- logger.warning(f'Skipping #{issue} as it is missing iid or title.')- continue-- # Handle None body for PRs- body = (- issue.get('description') if issue.get('description') is not None else ''- )- (- closing_issues,- closing_issues_numbers,- review_comments,- review_threads,- thread_ids,- ) = self.download_pr_metadata(issue['iid'], comment_id=comment_id)- head_branch = issue['source_branch']-- # Get PR thread comments- thread_comments = self.get_pr_comments(issue['iid'], comment_id=comment_id)-- closing_issues = self.get_context_from_external_issues_references(- closing_issues,- closing_issues_numbers,- body,- review_comments,- review_threads,- thread_comments,- )-- issue_details = Issue(- owner=self.owner,- repo=self.repo,- number=issue['iid'],- title=issue['title'],- body=body,- closing_issues=closing_issues,- review_comments=review_comments,- review_threads=review_threads,- thread_ids=thread_ids,- head_branch=head_branch,- thread_comments=thread_comments,- )-- converted_issues.append(issue_details)-- return converted_issuesdiff --git a/openhands/resolver/interfaces/issue_definitions.py b/openhands/resolver/interfaces/issue_definitions.pydeleted file mode 100644index cf1125fe59..0000000000--- a/openhands/resolver/interfaces/issue_definitions.py+++ /dev/null@@ -1,422 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import json-import os-import re-from typing import Any, ClassVar--import jinja2--from openhands.core.config import LLMConfig-from openhands.events.event import Event-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.issue import (- Issue,- IssueHandlerInterface,- ReviewThread,-)-from openhands.resolver.utils import extract_image_urls---class ServiceContext:- issue_type: ClassVar[str]- default_git_patch: ClassVar[str] = 'No changes made yet'-- def __init__(self, strategy: IssueHandlerInterface, llm_config: LLMConfig | None):- self._strategy = strategy- if llm_config is not None:- self.llm = LLM(llm_config, service_id='resolver')-- def set_strategy(self, strategy: IssueHandlerInterface) -> None:- self._strategy = strategy---# Strategy context interface-class ServiceContextPR(ServiceContext):- issue_type: ClassVar[str] = 'pr'-- def __init__(self, strategy: IssueHandlerInterface, llm_config: LLMConfig):- super().__init__(strategy, llm_config)-- def get_clone_url(self) -> str:- return self._strategy.get_clone_url()-- def download_issues(self) -> list[Any]:- return self._strategy.download_issues()-- def guess_success(- self,- issue: Issue,- history: list[Event],- git_patch: str | None = None,- ) -> tuple[bool, None | list[bool], str]:- """Guess if the issue is fixed based on the history, issue description and git patch.-- Args:- issue: The issue to check- history: The agent's history- git_patch: Optional git patch showing the changes made- """- last_message = history[-1].message-- issues_context = json.dumps(issue.closing_issues, indent=4)- success_list = []- explanation_list = []-- # Handle PRs with file-specific review comments- if issue.review_threads:- for review_thread in issue.review_threads:- if issues_context and last_message:- success, explanation = self._check_review_thread(- review_thread, issues_context, last_message, git_patch- )- else:- success, explanation = False, 'Missing context or message'- success_list.append(success)- explanation_list.append(explanation)- # Handle PRs with only thread comments (no file-specific review comments)- elif issue.thread_comments:- if issue.thread_comments and issues_context and last_message:- success, explanation = self._check_thread_comments(- issue.thread_comments, issues_context, last_message, git_patch- )- else:- success, explanation = (- False,- 'Missing thread comments, context or message',- )- success_list.append(success)- explanation_list.append(explanation)- elif issue.review_comments:- # Handle PRs with only review comments (no file-specific review comments or thread comments)- if issue.review_comments and issues_context and last_message:- success, explanation = self._check_review_comments(- issue.review_comments, issues_context, last_message, git_patch- )- else:- success, explanation = (- False,- 'Missing review comments, context or message',- )- success_list.append(success)- explanation_list.append(explanation)- else:- # No review comments, thread comments, or file-level review comments found- return False, None, 'No feedback was found to process'-- # Return overall success (all must be true) and explanations- if not success_list:- return False, None, 'No feedback was processed'- return all(success_list), success_list, json.dumps(explanation_list)-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- return self._strategy.get_converted_issues(issue_numbers, comment_id)-- def get_instruction(- self,- issue: Issue,- user_instructions_prompt_template: str,- conversation_instructions_prompt_template: str,- repo_instruction: str | None = None,- ) -> tuple[str, str, list[str]]:- """Generate instruction for the agent."""- user_instruction_template = jinja2.Template(user_instructions_prompt_template)- conversation_instructions_template = jinja2.Template(- conversation_instructions_prompt_template- )- images = []-- issues_str = None- if issue.closing_issues:- issues_str = json.dumps(issue.closing_issues, indent=4)- images.extend(extract_image_urls(issues_str))-- # Handle PRs with review comments- review_comments_str = None- if issue.review_comments:- review_comments_str = json.dumps(issue.review_comments, indent=4)- images.extend(extract_image_urls(review_comments_str))-- # Handle PRs with file-specific review comments- review_thread_str = None- review_thread_file_str = None- if issue.review_threads:- review_threads = [- review_thread.comment for review_thread in issue.review_threads- ]- review_thread_files = []- for review_thread in issue.review_threads:- review_thread_files.extend(review_thread.files)- review_thread_str = json.dumps(review_threads, indent=4)- review_thread_file_str = json.dumps(review_thread_files, indent=4)- images.extend(extract_image_urls(review_thread_str))-- # Format thread comments if they exist- thread_context = ''- if issue.thread_comments:- thread_context = '\n---\n'.join(issue.thread_comments)- images.extend(extract_image_urls(thread_context))-- user_instruction = user_instruction_template.render(- review_comments=review_comments_str,- review_threads=review_thread_str,- files=review_thread_file_str,- thread_context=thread_context,- )-- conversation_instructions = conversation_instructions_template.render(- issues=issues_str, repo_instruction=repo_instruction- )-- return user_instruction, conversation_instructions, images-- def _check_feedback_with_llm(self, prompt: str) -> tuple[bool, str]:- """Helper function to check feedback with LLM and parse response."""- response = self.llm.completion(messages=[{'role': 'user', 'content': prompt}])-- answer = response.choices[0].message.content.strip()- pattern = r'--- success\n*(true|false)\n*--- explanation*\n((?:.|\n)*)'- match = re.search(pattern, answer)- if match:- return match.group(1).lower() == 'true', match.group(2).strip()- return False, f'Failed to decode answer from LLM response: {answer}'-- def _check_review_thread(- self,- review_thread: ReviewThread,- issues_context: str,- last_message: str,- git_patch: str | None = None,- ) -> tuple[bool, str]:- """Check if a review thread's feedback has been addressed."""- files_context = json.dumps(review_thread.files, indent=4)-- with open(- os.path.join(- os.path.dirname(__file__),- '../prompts/guess_success/pr-feedback-check.jinja',- ),- 'r',- ) as f:- template = jinja2.Template(f.read())-- prompt = template.render(- issue_context=issues_context,- feedback=review_thread.comment,- files_context=files_context,- last_message=last_message,- git_patch=git_patch or self.default_git_patch,- )-- return self._check_feedback_with_llm(prompt)-- def _check_thread_comments(- self,- thread_comments: list[str],- issues_context: str,- last_message: str,- git_patch: str | None = None,- ) -> tuple[bool, str]:- """Check if thread comments feedback has been addressed."""- thread_context = '\n---\n'.join(thread_comments)-- with open(- os.path.join(- os.path.dirname(__file__),- '../prompts/guess_success/pr-thread-check.jinja',- ),- 'r',- ) as f:- template = jinja2.Template(f.read())-- prompt = template.render(- issue_context=issues_context,- thread_context=thread_context,- last_message=last_message,- git_patch=git_patch or self.default_git_patch,- )-- return self._check_feedback_with_llm(prompt)-- def _check_review_comments(- self,- review_comments: list[str],- issues_context: str,- last_message: str,- git_patch: str | None = None,- ) -> tuple[bool, str]:- """Check if review comments feedback has been addressed."""- review_context = '\n---\n'.join(review_comments)-- with open(- os.path.join(- os.path.dirname(__file__),- '../prompts/guess_success/pr-review-check.jinja',- ),- 'r',- ) as f:- template = jinja2.Template(f.read())-- prompt = template.render(- issue_context=issues_context,- review_context=review_context,- last_message=last_message,- git_patch=git_patch or self.default_git_patch,- )-- return self._check_feedback_with_llm(prompt)---class ServiceContextIssue(ServiceContext):- issue_type: ClassVar[str] = 'issue'-- def __init__(self, strategy: IssueHandlerInterface, llm_config: LLMConfig | None):- super().__init__(strategy, llm_config)-- def get_base_url(self) -> str:- return self._strategy.get_base_url()-- def get_branch_url(self, branch_name: str) -> str:- return self._strategy.get_branch_url(branch_name)-- def get_download_url(self) -> str:- return self._strategy.get_download_url()-- def get_clone_url(self) -> str:- return self._strategy.get_clone_url()-- def get_graphql_url(self) -> str:- return self._strategy.get_graphql_url()-- def get_headers(self) -> dict[str, str]:- return self._strategy.get_headers()-- def get_authorize_url(self) -> str:- return self._strategy.get_authorize_url()-- def get_pull_url(self, pr_number: int) -> str:- return self._strategy.get_pull_url(pr_number)-- def get_compare_url(self, branch_name: str) -> str:- return self._strategy.get_compare_url(branch_name)-- def download_issues(self) -> list[Any]:- return self._strategy.download_issues()-- def get_branch_name(- self,- base_branch_name: str,- ) -> str:- return self._strategy.get_branch_name(base_branch_name)-- def branch_exists(self, branch_name: str) -> bool:- return self._strategy.branch_exists(branch_name)-- def get_default_branch_name(self) -> str:- return self._strategy.get_default_branch_name()-- def create_pull_request(self, data: dict[str, Any] | None = None) -> dict[str, Any]:- if data is None:- data = {}- return self._strategy.create_pull_request(data)-- def request_reviewers(self, reviewer: str, pr_number: int) -> None:- return self._strategy.request_reviewers(reviewer, pr_number)-- def reply_to_comment(self, pr_number: int, comment_id: str, reply: str) -> None:- return self._strategy.reply_to_comment(pr_number, comment_id, reply)-- def send_comment_msg(self, issue_number: int, msg: str) -> None:- return self._strategy.send_comment_msg(issue_number, msg)-- def get_issue_comments(- self, issue_number: int, comment_id: int | None = None- ) -> list[str] | None:- return self._strategy.get_issue_comments(issue_number, comment_id)-- def get_instruction(- self,- issue: Issue,- user_instructions_prompt_template: str,- conversation_instructions_prompt_template: str,- repo_instruction: str | None = None,- ) -> tuple[str, str, list[str]]:- """Generate instruction for the agent."""- # Format thread comments if they exist- thread_context = ''- if issue.thread_comments:- thread_context = '\n\nIssue Thread Comments:\n' + '\n---\n'.join(- issue.thread_comments- )-- images = []- images.extend(extract_image_urls(issue.body))- images.extend(extract_image_urls(thread_context))-- user_instructions_template = jinja2.Template(user_instructions_prompt_template)- user_instructions = user_instructions_template.render(- body=issue.title + '\n\n' + issue.body + thread_context- ) # Issue body and comments-- conversation_instructions_template = jinja2.Template(- conversation_instructions_prompt_template- )- conversation_instructions = conversation_instructions_template.render(- repo_instruction=repo_instruction,- )-- return user_instructions, conversation_instructions, images-- def guess_success(- self, issue: Issue, history: list[Event], git_patch: str | None = None- ) -> tuple[bool, None | list[bool], str]:- """Guess if the issue is fixed based on the history and the issue description.-- Args:- issue: The issue to check- history: The agent's history- git_patch: Optional git patch showing the changes made- """- last_message = history[-1].message- # Include thread comments in the prompt if they exist- issue_context = issue.body- if issue.thread_comments:- issue_context += '\n\nIssue Thread Comments:\n' + '\n---\n'.join(- issue.thread_comments- )-- with open(- os.path.join(- os.path.dirname(__file__),- '../prompts/guess_success/issue-success-check.jinja',- ),- 'r',- ) as f:- template = jinja2.Template(f.read())- prompt = template.render(- issue_context=issue_context,- last_message=last_message,- git_patch=git_patch or self.default_git_patch,- )-- response = self.llm.completion(messages=[{'role': 'user', 'content': prompt}])-- answer = response.choices[0].message.content.strip()- pattern = r'--- success\n*(true|false)\n*--- explanation*\n((?:.|\n)*)'- match = re.search(pattern, answer)- if match:- return match.group(1).lower() == 'true', None, match.group(2)-- return False, None, f'Failed to decode answer from LLM response: {answer}'-- def get_converted_issues(- self, issue_numbers: list[int] | None = None, comment_id: int | None = None- ) -> list[Issue]:- return self._strategy.get_converted_issues(issue_numbers, comment_id)diff --git a/openhands/resolver/io_utils.py b/openhands/resolver/io_utils.pydeleted file mode 100644index 563d1c51ee..0000000000--- a/openhands/resolver/io_utils.py+++ /dev/null@@ -1,24 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import json-from typing import Iterable--from openhands.resolver.resolver_output import ResolverOutput---def load_all_resolver_outputs(output_jsonl: str) -> Iterable[ResolverOutput]:- with open(output_jsonl, 'r') as f:- for line in f:- yield ResolverOutput.model_validate(json.loads(line))---def load_single_resolver_output(output_jsonl: str, issue_number: int) -> ResolverOutput:- for resolver_output in load_all_resolver_outputs(output_jsonl):- if resolver_output.issue.number == issue_number:- return resolver_output- raise ValueError(f'Issue number {issue_number} not found in {output_jsonl}')diff --git a/openhands/resolver/issue_handler_factory.py b/openhands/resolver/issue_handler_factory.pydeleted file mode 100644index ddab05432c..0000000000--- a/openhands/resolver/issue_handler_factory.py+++ /dev/null@@ -1,211 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from openhands.core.config import LLMConfig-from openhands.integrations.provider import ProviderType-from openhands.resolver.interfaces.azure_devops import AzureDevOpsIssueHandler-from openhands.resolver.interfaces.bitbucket import (- BitbucketIssueHandler,- BitbucketPRHandler,-)-from openhands.resolver.interfaces.bitbucket_data_center import (- BitbucketDCIssueHandler,- BitbucketDCPRHandler,-)-from openhands.resolver.interfaces.forgejo import (- ForgejoIssueHandler,- ForgejoPRHandler,-)-from openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandler-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandler-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)---class IssueHandlerFactory:- def __init__(- self,- owner: str,- repo: str,- token: str,- username: str,- platform: ProviderType,- base_domain: str,- issue_type: str,- llm_config: LLMConfig,- ) -> None:- self.owner = owner- self.repo = repo- self.token = token- self.username = username- self.platform = platform- self.base_domain = base_domain- self.issue_type = issue_type- self.llm_config = llm_config-- def create(self) -> ServiceContextIssue | ServiceContextPR:- if self.issue_type == 'issue':- if self.platform == ProviderType.GITHUB:- return ServiceContextIssue(- GithubIssueHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.GITLAB:- return ServiceContextIssue(- GitlabIssueHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.BITBUCKET:- return ServiceContextIssue(- BitbucketIssueHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.BITBUCKET_DATA_CENTER:- return ServiceContextIssue(- BitbucketDCIssueHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.FORGEJO:- return ServiceContextIssue(- ForgejoIssueHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.AZURE_DEVOPS:- # Parse owner as organization/project- parts = self.owner.split('/')- if len(parts) < 2:- raise ValueError(- f'Invalid Azure DevOps owner format: {self.owner}. Expected format: organization/project'- )-- organization = parts[0]- project = parts[1]-- return ServiceContextIssue(- AzureDevOpsIssueHandler(- self.token,- organization,- project,- self.repo,- ),- self.llm_config,- )- else:- raise ValueError(f'Unsupported platform: {self.platform}')- elif self.issue_type == 'pr':- if self.platform == ProviderType.GITHUB:- return ServiceContextPR(- GithubPRHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.GITLAB:- return ServiceContextPR(- GitlabPRHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.BITBUCKET:- return ServiceContextPR(- BitbucketPRHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.BITBUCKET_DATA_CENTER:- return ServiceContextPR(- BitbucketDCPRHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.FORGEJO:- return ServiceContextPR(- ForgejoPRHandler(- self.owner,- self.repo,- self.token,- self.username,- self.base_domain,- ),- self.llm_config,- )- elif self.platform == ProviderType.AZURE_DEVOPS:- # Parse owner as organization/project- parts = self.owner.split('/')- if len(parts) < 2:- raise ValueError(- f'Invalid Azure DevOps owner format: {self.owner}. Expected format: organization/project'- )-- organization = parts[0]- project = parts[1]-- # For now, use the same handler for both issues and PRs- return ServiceContextPR(- AzureDevOpsIssueHandler(- self.token,- organization,- project,- self.repo,- ),- self.llm_config,- )- else:- raise ValueError(f'Unsupported platform: {self.platform}')- else:- raise ValueError(f'Invalid issue type: {self.issue_type}')diff --git a/openhands/resolver/issue_resolver.py b/openhands/resolver/issue_resolver.pydeleted file mode 100644index 1d1821b66b..0000000000--- a/openhands/resolver/issue_resolver.py+++ /dev/null@@ -1,679 +0,0 @@-# flake8: noqa: E501--# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import asyncio-import dataclasses-import json-import os-import pathlib-import shutil-import subprocess-from argparse import Namespace-from typing import Any-from uuid import uuid4--from termcolor import colored--import openhands-from openhands.controller.state.state import State-from openhands.core.config import AgentConfig, OpenHandsConfig, SandboxConfig-from openhands.core.config.utils import load_openhands_config-from openhands.core.logger import openhands_logger as logger-from openhands.core.main import create_runtime, run_controller-from openhands.events.action import CmdRunAction, MessageAction-from openhands.events.event import Event-from openhands.events.observation import (- CmdOutputObservation,- ErrorObservation,- Observation,-)-from openhands.events.stream import EventStreamSubscriber-from openhands.integrations.service_types import ProviderType-from openhands.llm.llm_registry import LLMRegistry-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)-from openhands.resolver.issue_handler_factory import IssueHandlerFactory-from openhands.resolver.resolver_output import ResolverOutput-from openhands.resolver.utils import (- codeact_user_response,- get_unique_uid,- identify_token,- reset_logger_for_multiprocessing,-)-from openhands.runtime.base import Runtime-from openhands.utils.async_utils import GENERAL_TIMEOUT, call_async_from_sync--# Don't make this configurable for now, unless we have other competitive agents-AGENT_CLASS = 'CodeActAgent'---class IssueResolver:- GITLAB_CI = os.getenv('GITLAB_CI') == 'true'-- def __init__(self, args: Namespace) -> None:- """Initialize the IssueResolver with the given parameters.-- Params initialized:- owner: Owner of the repo.- repo: Repository name.- token: Token to access the repository.- username: Username to access the repository.- platform: Platform of the repository.- runtime_container_image: Container image to use.- max_iterations: Maximum number of iterations to run.- output_dir: Output directory to write the results.- llm_config: Configuration for the language model.- prompt_template: Prompt template to use.- issue_type: Type of issue to resolve (issue or pr).- repo_instruction: Repository instruction to use.- issue_number: Issue number to resolve.- comment_id: Optional ID of a specific comment to focus on.- base_domain: The base domain for the git server.- """- parts = args.selected_repo.rsplit('/', 1)- if len(parts) < 2:- raise ValueError('Invalid repository format. Expected owner/repo')- owner, repo = parts-- token = (- args.token- or os.getenv('GITHUB_TOKEN')- or os.getenv('GITLAB_TOKEN')- or os.getenv('BITBUCKET_TOKEN')- or os.getenv('AZURE_DEVOPS_TOKEN')- or os.getenv('FORGEJO_TOKEN')- )- username = args.username if args.username else os.getenv('GIT_USERNAME')- if not username:- raise ValueError('Username is required.')-- if not token:- raise ValueError('Token is required.')-- platform = call_async_from_sync(- identify_token,- GENERAL_TIMEOUT,- token,- args.base_domain,- )-- repo_instruction = None- if args.repo_instruction_file:- with open(args.repo_instruction_file, 'r') as f:- repo_instruction = f.read()-- issue_type = args.issue_type-- # Read the prompt template- prompt_file = args.prompt_file- if prompt_file is None:- if issue_type == 'issue':- prompt_file = os.path.join(- os.path.dirname(__file__), 'prompts/resolve/basic-with-tests.jinja'- )- else:- prompt_file = os.path.join(- os.path.dirname(__file__), 'prompts/resolve/basic-followup.jinja'- )- with open(prompt_file, 'r') as f:- user_instructions_prompt_template = f.read()-- with open(- prompt_file.replace('.jinja', '-conversation-instructions.jinja')- ) as f:- conversation_instructions_prompt_template = f.read()-- base_domain = args.base_domain- if base_domain is None:- base_domain = (- 'github.com'- if platform == ProviderType.GITHUB- else 'gitlab.com'- if platform == ProviderType.GITLAB- else 'bitbucket.org'- if platform == ProviderType.BITBUCKET- else 'bitbucket.example.com'- if platform == ProviderType.BITBUCKET_DATA_CENTER- else 'dev.azure.com'- )-- self.output_dir = args.output_dir- self.issue_type = issue_type- self.issue_number = args.issue_number-- self.workspace_base = self.build_workspace_base(- self.output_dir, self.issue_type, self.issue_number- )-- self.max_iterations = args.max_iterations-- self.app_config = self.update_openhands_config(- load_openhands_config(),- self.max_iterations,- self.workspace_base,- args.base_container_image,- args.runtime_container_image,- args.is_experimental,- args.runtime,- )-- self.owner = owner- self.repo = repo- self.platform = platform- self.user_instructions_prompt_template = user_instructions_prompt_template- self.conversation_instructions_prompt_template = (- conversation_instructions_prompt_template- )- self.repo_instruction = repo_instruction- self.comment_id = args.comment_id-- factory = IssueHandlerFactory(- owner=self.owner,- repo=self.repo,- token=token,- username=username,- platform=self.platform,- base_domain=base_domain,- issue_type=self.issue_type,- llm_config=self.app_config.get_llm_config(),- )- self.issue_handler = factory.create()-- @classmethod- def update_openhands_config(- cls,- config: OpenHandsConfig,- max_iterations: int,- workspace_base: str,- base_container_image: str | None,- runtime_container_image: str | None,- is_experimental: bool,- runtime: str | None = None,- ) -> OpenHandsConfig:- config.default_agent = 'CodeActAgent'- # Use provided runtime or fallback to config value or default to 'docker'- config.runtime = runtime or config.runtime or 'docker'- config.max_budget_per_task = 4- config.max_iterations = max_iterations-- # do not mount workspace- config.workspace_base = workspace_base- config.workspace_mount_path = workspace_base- config.agents = {'CodeActAgent': AgentConfig(disabled_microagents=['github'])}-- cls.update_sandbox_config(- config,- base_container_image,- runtime_container_image,- is_experimental,- )-- return config-- @classmethod- def update_sandbox_config(- cls,- openhands_config: OpenHandsConfig,- base_container_image: str | None,- runtime_container_image: str | None,- is_experimental: bool,- ) -> None:- if runtime_container_image is not None and base_container_image is not None:- raise ValueError('Cannot provide both runtime and base container images.')-- if (- runtime_container_image is None- and base_container_image is None- and not is_experimental- ):- runtime_container_image = (- f'ghcr.io/openhands/runtime:{openhands.__version__}-nikolaik'- )-- # Convert container image values to string or None- container_base = (- str(base_container_image) if base_container_image is not None else None- )- container_runtime = (- str(runtime_container_image)- if runtime_container_image is not None- else None- )-- sandbox_config = SandboxConfig(- base_container_image=container_base,- runtime_container_image=container_runtime,- enable_auto_lint=False,- use_host_network=False,- timeout=300,- )-- # Configure sandbox for GitLab CI environment- if cls.GITLAB_CI:- sandbox_config.local_runtime_url = os.getenv(- 'LOCAL_RUNTIME_URL', 'http://localhost'- )- user_id = os.getuid() if hasattr(os, 'getuid') else 1000- if user_id == 0:- sandbox_config.user_id = get_unique_uid()-- openhands_config.sandbox.base_container_image = (- sandbox_config.base_container_image- )- openhands_config.sandbox.runtime_container_image = (- sandbox_config.runtime_container_image- )- openhands_config.sandbox.enable_auto_lint = sandbox_config.enable_auto_lint- openhands_config.sandbox.use_host_network = sandbox_config.use_host_network- openhands_config.sandbox.timeout = sandbox_config.timeout- openhands_config.sandbox.local_runtime_url = sandbox_config.local_runtime_url- openhands_config.sandbox.user_id = sandbox_config.user_id-- def initialize_runtime(- self,- runtime: Runtime,- ) -> None:- """Initialize the runtime for the agent.-- This function is called before the runtime is used to run the agent.- It sets up git configuration and runs the setup script if it exists.- """- logger.info('-' * 30)- logger.info('BEGIN Runtime Completion Fn')- logger.info('-' * 30)- obs: Observation-- action = CmdRunAction(command='cd /workspace')- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:- raise RuntimeError(f'Failed to change directory to /workspace.\n{obs}')-- if self.platform == ProviderType.GITLAB and self.GITLAB_CI:- action = CmdRunAction(command='sudo chown -R 1001:0 /workspace/*')- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})-- action = CmdRunAction(command='git config --global core.pager ""')- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:- raise RuntimeError(f'Failed to set git config.\n{obs}')-- # Run setup script if it exists- logger.info('Checking for .openhands/setup.sh script...')- runtime.maybe_run_setup_script()-- # Setup git hooks if they exist- logger.info('Checking for .openhands/pre-commit.sh script...')- runtime.maybe_setup_git_hooks()-- async def complete_runtime(- self,- runtime: Runtime,- base_commit: str,- ) -> dict[str, Any]:- """Complete the runtime for the agent.-- This function is called before the runtime is used to run the agent.- If you need to do something in the sandbox to get the correctness metric after- the agent has run, modify this function.- """- logger.info('-' * 30)- logger.info('BEGIN Runtime Completion Fn')- logger.info('-' * 30)- obs: Observation-- action = CmdRunAction(command='cd /workspace')- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:- raise RuntimeError(- f'Failed to change directory to /workspace. Observation: {obs}'- )-- action = CmdRunAction(command='git config --global core.pager ""')- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:- raise RuntimeError(f'Failed to set git config. Observation: {obs}')-- action = CmdRunAction(- command='git config --global --add safe.directory /workspace'- )- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:- raise RuntimeError(f'Failed to set git config. Observation: {obs}')-- if self.platform == ProviderType.GITLAB and self.GITLAB_CI:- action = CmdRunAction(command='sudo git add -A')- else:- action = CmdRunAction(command='git add -A')-- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:- raise RuntimeError(f'Failed to git add. Observation: {obs}')-- n_retries = 0- git_patch = None- while n_retries < 5:- action = CmdRunAction(command=f'git diff --no-color --cached {base_commit}')- action.set_hard_timeout(600 + 100 * n_retries)- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- n_retries += 1- if isinstance(obs, CmdOutputObservation):- if obs.exit_code == 0:- git_patch = obs.content.strip()- break- else:- logger.info('Failed to get git diff, retrying...')- await asyncio.sleep(10)- elif isinstance(obs, ErrorObservation):- logger.error(f'Error occurred: {obs.content}. Retrying...')- await asyncio.sleep(10)- else:- raise ValueError(f'Unexpected observation type: {type(obs)}')-- logger.info('-' * 30)- logger.info('END Runtime Completion Fn')- logger.info('-' * 30)- return {'git_patch': git_patch}-- @staticmethod- def build_workspace_base(- output_dir: str, issue_type: str, issue_number: int- ) -> str:- workspace_base = os.path.join(- output_dir, 'workspace', f'{issue_type}_{issue_number}'- )- return os.path.abspath(workspace_base)-- async def process_issue(- self,- issue: Issue,- base_commit: str,- issue_handler: ServiceContextIssue | ServiceContextPR,- reset_logger: bool = False,- ) -> ResolverOutput:- # Setup the logger properly, so you can run multi-processing to parallelize processing- if reset_logger:- log_dir = os.path.join(self.output_dir, 'infer_logs')- reset_logger_for_multiprocessing(logger, str(issue.number), log_dir)- else:- logger.info(f'Starting fixing issue {issue.number}.')-- # write the repo to the workspace- if os.path.exists(self.workspace_base):- shutil.rmtree(self.workspace_base)- shutil.copytree(os.path.join(self.output_dir, 'repo'), self.workspace_base)-- llm_registry = LLMRegistry(self.app_config)- runtime = create_runtime(self.app_config, llm_registry)- await runtime.connect()-- def on_event(evt: Event) -> None:- logger.info(evt)-- runtime.event_stream.subscribe(- EventStreamSubscriber.MAIN, on_event, str(uuid4())- )-- self.initialize_runtime(runtime)-- instruction, conversation_instructions, images_urls = (- issue_handler.get_instruction(- issue,- self.user_instructions_prompt_template,- self.conversation_instructions_prompt_template,- self.repo_instruction,- )- )- # Here's how you can run the agent (similar to the `main` function) and get the final task state- action = MessageAction(content=instruction, image_urls=images_urls)- try:- state: State | None = await run_controller(- config=self.app_config,- initial_user_action=action,- runtime=runtime,- fake_user_response_fn=codeact_user_response,- conversation_instructions=conversation_instructions,- )- if state is None:- raise RuntimeError('Failed to run the agent.')- except (ValueError, RuntimeError) as e:- error_msg = f'Agent failed with error: {str(e)}'- logger.error(error_msg)- state = None- last_error: str | None = error_msg-- # Get git patch- return_val = await self.complete_runtime(runtime, base_commit)- git_patch = return_val['git_patch']- logger.info(- f'Got git diff for instance {issue.number}:\n--------\n{git_patch}\n--------'- )-- # Serialize histories and set defaults for failed state- if state is None:- histories = []- metrics = None- success = False- comment_success = None- result_explanation = 'Agent failed to run'- last_error = 'Agent failed to run or crashed'- else:- histories = [dataclasses.asdict(event) for event in state.history]- metrics = state.metrics.get() if state.metrics else None- # determine success based on the history, issue description and git patch- success, comment_success, result_explanation = issue_handler.guess_success(- issue, state.history, git_patch- )-- if issue_handler.issue_type == 'pr' and comment_success:- success_log = 'I have updated the PR and resolved some of the issues that were cited in the pull request review. Specifically, I identified the following revision requests, and all the ones that I think I successfully resolved are checked off. All the unchecked ones I was not able to resolve, so manual intervention may be required:\n'- try:- explanations = json.loads(result_explanation)- except json.JSONDecodeError:- logger.error(- f'Failed to parse result_explanation as JSON: {result_explanation}'- )- explanations = [- str(result_explanation)- ] # Use raw string as fallback-- for success_indicator, explanation in zip(- comment_success, explanations- ):- status = (- colored('[X]', 'red')- if success_indicator- else colored('[ ]', 'red')- )- bullet_point = colored('-', 'yellow')- success_log += f'\n{bullet_point} {status}: {explanation}'- logger.info(success_log)- last_error = state.last_error if state.last_error else None-- # Save the output- output = ResolverOutput(- issue=issue,- issue_type=issue_handler.issue_type,- instruction=instruction,- base_commit=base_commit,- git_patch=git_patch,- history=histories,- metrics=metrics,- success=success,- comment_success=comment_success,- result_explanation=result_explanation,- error=last_error,- )- return output-- def extract_issue(self) -> Issue:- # Load dataset- issues: list[Issue] = self.issue_handler.get_converted_issues(- issue_numbers=[self.issue_number], comment_id=self.comment_id- )-- if not issues:- raise ValueError(- f'No issues found for issue number {self.issue_number}. Please verify that:\n'- f'1. The issue/PR #{self.issue_number} exists in the repository {self.owner}/{self.repo}\n'- f'2. You have the correct permissions to access it\n'- f'3. The repository name is spelled correctly'- )-- return issues[0]-- async def resolve_issue(- self,- reset_logger: bool = False,- ) -> None:- """Resolve a single issue.-- Args:- reset_logger: Whether to reset the logger for multiprocessing.- """- issue = self.extract_issue()-- if self.comment_id is not None:- if (- self.issue_type == 'pr'- and not issue.review_comments- and not issue.review_threads- and not issue.thread_comments- ):- raise ValueError(- f'Comment ID {self.comment_id} did not have a match for issue {issue.number}'- )-- if self.issue_type == 'issue' and not issue.thread_comments:- raise ValueError(- f'Comment ID {self.comment_id} did not have a match for issue {issue.number}'- )-- # TEST METADATA- model_name = self.app_config.get_llm_config().model.split('/')[-1]-- pathlib.Path(self.output_dir).mkdir(parents=True, exist_ok=True)- pathlib.Path(os.path.join(self.output_dir, 'infer_logs')).mkdir(- parents=True, exist_ok=True- )- logger.info(f'Using output directory: {self.output_dir}')-- # checkout the repo- repo_dir = os.path.join(self.output_dir, 'repo')- if not os.path.exists(repo_dir):- checkout_output = subprocess.check_output(- [- 'git',- 'clone',- self.issue_handler.get_clone_url(),- f'{self.output_dir}/repo',- ]- ).decode('utf-8')- if 'fatal' in checkout_output:- raise RuntimeError(f'Failed to clone repository: {checkout_output}')-- # get the commit id of current repo for reproducibility- base_commit = (- subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir)- .decode('utf-8')- .strip()- )- logger.info(f'Base commit: {base_commit}')-- if self.repo_instruction is None:- # Check for .openhands_instructions file in the workspace directory- openhands_instructions_path = os.path.join(- repo_dir, '.openhands_instructions'- )- if os.path.exists(openhands_instructions_path):- with open(openhands_instructions_path, 'r') as f:- self.repo_instruction = f.read()-- # OUTPUT FILE- output_file = os.path.join(self.output_dir, 'output.jsonl')- logger.info(f'Writing output to {output_file}')-- # Check if this issue was already processed- if os.path.exists(output_file):- with open(output_file, 'r') as f:- for line in f:- data = ResolverOutput.model_validate_json(line)- if data.issue.number == self.issue_number:- logger.warning(- f'Issue {self.issue_number} was already processed. Skipping.'- )- return-- output_fp = open(output_file, 'a')-- logger.info(- f'Resolving issue {self.issue_number} with Agent {AGENT_CLASS}, model {model_name}, max iterations {self.max_iterations}.'- )-- try:- # checkout to pr branch if needed- if self.issue_type == 'pr':- branch_to_use = issue.head_branch- logger.info(- f'Checking out to PR branch {branch_to_use} for issue {issue.number}'- )-- if not branch_to_use:- raise ValueError('Branch name cannot be None')-- # Fetch the branch first to ensure it exists locally- fetch_cmd = ['git', 'fetch', 'origin', branch_to_use]- subprocess.check_output(- fetch_cmd,- cwd=repo_dir,- )-- # Checkout the branch- checkout_cmd = ['git', 'checkout', branch_to_use]- subprocess.check_output(- checkout_cmd,- cwd=repo_dir,- )-- base_commit = (- subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir)- .decode('utf-8')- .strip()- )-- output = await self.process_issue(- issue,- base_commit,- self.issue_handler,- reset_logger,- )- output_fp.write(output.model_dump_json() + '\n')- output_fp.flush()-- finally:- output_fp.close()- logger.info('Finished.')diff --git a/openhands/resolver/patching/README.md b/openhands/resolver/patching/README.mddeleted file mode 100644index e0c7b98eac..0000000000--- a/openhands/resolver/patching/README.md+++ /dev/null@@ -1,4 +0,0 @@-# Patching code--Originally from [whatthepatch](https://github.com/cscorley/whatthepatch)-(MIT license)diff --git a/openhands/resolver/patching/__init__.py b/openhands/resolver/patching/__init__.pydeleted file mode 100644index 165a623af5..0000000000--- a/openhands/resolver/patching/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-# -*- coding: utf-8 -*---from .apply import apply_diff-from .patch import parse_patch--__all__ = ['parse_patch', 'apply_diff']diff --git a/openhands/resolver/patching/apply.py b/openhands/resolver/patching/apply.pydeleted file mode 100644index 69e14c9d21..0000000000--- a/openhands/resolver/patching/apply.py+++ /dev/null@@ -1,135 +0,0 @@-# -*- coding: utf-8 -*---# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import os.path-import subprocess-import tempfile--from .exceptions import HunkApplyException, SubprocessException-from .patch import Change, diffobj-from .snippets import remove, which---def _apply_diff_with_subprocess(- diff: diffobj, lines: list[str], reverse: bool = False-) -> tuple[list[str], list[str] | None]:- # call out to patch program- patchexec = which('patch')- if not patchexec:- raise SubprocessException('cannot find patch program', code=-1)-- tempdir = tempfile.gettempdir()-- filepath = os.path.join(tempdir, 'wtp-' + str(hash(diff.header)))- oldfilepath = filepath + '.old'- newfilepath = filepath + '.new'- rejfilepath = filepath + '.rej'- patchfilepath = filepath + '.patch'- with open(oldfilepath, 'w') as f:- f.write('\n'.join(lines) + '\n')-- with open(patchfilepath, 'w') as f:- f.write(diff.text)-- args = [- patchexec,- '--reverse' if reverse else '--forward',- '--quiet',- '--no-backup-if-mismatch',- '-o',- newfilepath,- '-i',- patchfilepath,- '-r',- rejfilepath,- oldfilepath,- ]- ret = subprocess.call(args)-- with open(newfilepath) as f:- lines = f.read().splitlines()-- try:- with open(rejfilepath) as f:- rejlines = f.read().splitlines()- except IOError:- rejlines = None-- remove(oldfilepath)- remove(newfilepath)- remove(rejfilepath)- remove(patchfilepath)-- # do this last to ensure files get cleaned up- if ret != 0:- raise SubprocessException('patch program failed', code=ret)-- return lines, rejlines---def _reverse(changes: list[Change]) -> list[Change]:- def _reverse_change(c: Change) -> Change:- return c._replace(old=c.new, new=c.old)-- return [_reverse_change(c) for c in changes]---def apply_diff(- diff: diffobj, text: str | list[str], reverse: bool = False, use_patch: bool = False-) -> list[str]:- lines = text.splitlines() if isinstance(text, str) else list(text)-- if use_patch:- lines, _ = _apply_diff_with_subprocess(diff, lines, reverse)- return lines-- n_lines = len(lines)-- changes = _reverse(diff.changes) if reverse else diff.changes- # check that the source text matches the context of the diff- for old, new, line, hunk in changes:- # might have to check for line is None here for ed scripts- if old is not None and line is not None:- if old > n_lines:- raise HunkApplyException(- 'context line {n}, "{line}" does not exist in source'.format(- n=old, line=line- ),- hunk=hunk,- )- if lines[old - 1] != line:- # Try to normalize whitespace by replacing multiple spaces with a single space- # This helps with patches that have different indentation levels- normalized_line = ' '.join(line.split())- normalized_source = ' '.join(lines[old - 1].split())- if normalized_line != normalized_source:- raise HunkApplyException(- 'context line {n}, "{line}" does not match "{sl}"'.format(- n=old, line=line, sl=lines[old - 1]- ),- hunk=hunk,- )-- # for calculating the old line- r = 0- i = 0-- for old, new, line, hunk in changes:- if old is not None and new is None:- del lines[old - 1 - r + i]- r += 1- elif old is None and new is not None:- lines.insert(new - 1, line)- i += 1- elif old is not None and new is not None:- # Sometimes, people remove hunks from patches, making these- # numbers completely unreliable. Because they're jerks.- pass-- return linesdiff --git a/openhands/resolver/patching/exceptions.py b/openhands/resolver/patching/exceptions.pydeleted file mode 100644index 08171587da..0000000000--- a/openhands/resolver/patching/exceptions.py+++ /dev/null@@ -1,36 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-class PatchingException(Exception):- pass---class HunkException(PatchingException):- def __init__(self, msg: str, hunk: int | None = None) -> None:- self.hunk = hunk- if hunk is not None:- super().__init__('{msg}, in hunk #{n}'.format(msg=msg, n=hunk))- else:- super().__init__(msg)---class ApplyException(PatchingException):- pass---class SubprocessException(ApplyException):- def __init__(self, msg: str, code: int) -> None:- super().__init__(msg)- self.code = code---class HunkApplyException(HunkException, ApplyException, ValueError):- pass---class ParseException(HunkException, ValueError):- passdiff --git a/openhands/resolver/patching/patch.py b/openhands/resolver/patching/patch.pydeleted file mode 100644index 8e9162627a..0000000000--- a/openhands/resolver/patching/patch.py+++ /dev/null@@ -1,984 +0,0 @@-# -*- coding: utf-8 -*--# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import base64-import re-import zlib-from collections import namedtuple-from typing import Iterable--from . import exceptions-from .snippets import findall_regex, split_by_regex--header = namedtuple(- 'header',- 'index_path old_path old_version new_path new_version',-)--diffobj = namedtuple('diffobj', 'header changes text')-Change = namedtuple('Change', 'old new line hunk')--file_timestamp_str = '(.+?)(?:\t|:| +)(.*)'-# .+? was previously [^:\t\n\r\f\v]+--# general diff regex-diffcmd_header = re.compile('^diff.* (.+) (.+)$')-unified_header_index = re.compile('^Index: (.+)$')-unified_header_old_line = re.compile(r'^--- ' + file_timestamp_str + '$')-unified_header_new_line = re.compile(r'^\+\+\+ ' + file_timestamp_str + '$')-unified_hunk_start = re.compile(r'^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@(.*)$')-unified_change = re.compile('^([-+ ])(.*)$', re.MULTILINE)--context_header_old_line = re.compile(r'^\*\*\* ' + file_timestamp_str + '$')-context_header_new_line = re.compile('^--- ' + file_timestamp_str + '$')-context_hunk_start = re.compile(r'^\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*$')-context_hunk_old = re.compile(r'^\*\*\* (\d+),?(\d*) \*\*\*\*$')-context_hunk_new = re.compile(r'^--- (\d+),?(\d*) ----$')-context_change = re.compile('^([-+ !]) (.*)$')--ed_hunk_start = re.compile(r'^(\d+),?(\d*)([acd])$')-ed_hunk_end = re.compile('^.$')-# much like forward ed, but no 'c' type-rcs_ed_hunk_start = re.compile(r'^([ad])(\d+) ?(\d*)$')--default_hunk_start = re.compile(r'^(\d+),?(\d*)([acd])(\d+),?(\d*)$')-default_hunk_mid = re.compile('^---$')-default_change = re.compile('^([><]) (.*)$')--# Headers--# git has a special index header and no end part-git_diffcmd_header = re.compile('^diff --git a/(.+) b/(.+)$')-git_header_index = re.compile(r'^index ([a-f0-9]+)..([a-f0-9]+) ?(\d*)$')-git_header_old_line = re.compile('^--- (.+)$')-git_header_new_line = re.compile(r'^\+\+\+ (.+)$')-git_header_file_mode = re.compile(r'^(new|deleted) file mode \d{6}$')-git_header_binary_file = re.compile('^Binary files (.+) and (.+) differ')-git_binary_patch_start = re.compile(r'^GIT binary patch$')-git_binary_literal_start = re.compile(r'^literal (\d+)$')-git_binary_delta_start = re.compile(r'^delta (\d+)$')-base85string = re.compile(r'^[0-9A-Za-z!#$%&()*+;<=>?@^_`{|}~-]+$')--bzr_header_index = re.compile('=== (.+)')-bzr_header_old_line = unified_header_old_line-bzr_header_new_line = unified_header_new_line--svn_header_index = unified_header_index-svn_header_timestamp_version = re.compile(r'\((?:working copy|revision (\d+))\)')-svn_header_timestamp = re.compile(r'.*(\(.*\))$')--cvs_header_index = unified_header_index-cvs_header_rcs = re.compile(r'^RCS file: (.+)(?:,\w{1}$|$)')-cvs_header_timestamp = re.compile(r'(.+)\t([\d.]+)')-cvs_header_timestamp_colon = re.compile(r':([\d.]+)\t(.+)')-old_cvs_diffcmd_header = re.compile('^diff.* (.+):(.*) (.+):(.*)$')---def parse_patch(text: str | list[str]) -> Iterable[diffobj]:- lines = text.splitlines() if isinstance(text, str) else text-- # maybe use this to nuke all of those line endings?- # lines = [x.splitlines()[0] for x in lines]- lines = [x if len(x) == 0 else x.splitlines()[0] for x in lines]-- check = [- unified_header_index,- diffcmd_header,- cvs_header_rcs,- git_header_index,- context_header_old_line,- unified_header_old_line,- ]-- diffs = []- for c in check:- diffs = split_by_regex(lines, c)- if len(diffs) > 1:- break-- for diff in diffs:- difftext = '\n'.join(diff) + '\n'- h = parse_header(diff)- d = parse_diff(diff)- if h or d:- yield diffobj(header=h, changes=d, text=difftext)---def parse_header(text: str | list[str]) -> header | None:- h = parse_scm_header(text)- if h is None:- h = parse_diff_header(text)- return h---def parse_scm_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- check = [- (git_header_index, parse_git_header),- (old_cvs_diffcmd_header, parse_cvs_header),- (cvs_header_rcs, parse_cvs_header),- (svn_header_index, parse_svn_header),- ]-- for regex, parser in check:- diffs = findall_regex(lines, regex)- if len(diffs) > 0:- git_opt = findall_regex(lines, git_diffcmd_header)- if len(git_opt) > 0:- res = parser(lines)- if res:- old_path = res.old_path- new_path = res.new_path- if old_path.startswith('a/'):- old_path = old_path[2:]-- if new_path.startswith('b/'):- new_path = new_path[2:]-- return header(- index_path=res.index_path,- old_path=old_path,- old_version=res.old_version,- new_path=new_path,- new_version=res.new_version,- )- else:- res = parser(lines)-- return res-- return None---def parse_diff_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- check = [- (unified_header_new_line, parse_unified_header),- (context_header_old_line, parse_context_header),- (diffcmd_header, parse_diffcmd_header),- # TODO:- # git_header can handle version-less unified headers, but- # will trim a/ and b/ in the paths if they exist...- (git_header_new_line, parse_git_header),- ]-- for regex, parser in check:- diffs = findall_regex(lines, regex)- if len(diffs) > 0:- return parser(lines)-- return None # no header?---def parse_diff(text: str | list[str]) -> list[Change] | None:- if isinstance(text, str):- lines = text.splitlines()- else:- lines = text-- check = [- (unified_hunk_start, parse_unified_diff),- (context_hunk_start, parse_context_diff),- (default_hunk_start, parse_default_diff),- (ed_hunk_start, parse_ed_diff),- (rcs_ed_hunk_start, parse_rcs_ed_diff),- (git_binary_patch_start, parse_git_binary_diff),- ]-- for hunk, parser in check:- diffs = findall_regex(lines, hunk)- if len(diffs) > 0:- return parser(lines)- return None---def parse_git_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- old_version = None- new_version = None- old_path = None- new_path = None- cmd_old_path = None- cmd_new_path = None- for line in lines:- hm = git_diffcmd_header.match(line)- if hm:- cmd_old_path = hm.group(1)- cmd_new_path = hm.group(2)- continue-- g = git_header_index.match(line)- if g:- old_version = g.group(1)- new_version = g.group(2)- continue-- # git always has its own special headers- o = git_header_old_line.match(line)- if o:- old_path = o.group(1)-- n = git_header_new_line.match(line)- if n:- new_path = n.group(1)-- binary = git_header_binary_file.match(line)- if binary:- old_path = binary.group(1)- new_path = binary.group(2)-- if old_path and new_path:- if old_path.startswith('a/'):- old_path = old_path[2:]-- if new_path.startswith('b/'):- new_path = new_path[2:]- return header(- index_path=None,- old_path=old_path,- old_version=old_version,- new_path=new_path,- new_version=new_version,- )-- # if we go through all of the text without finding our normal info,- # use the cmd if available- if cmd_old_path and cmd_new_path and old_version and new_version:- if cmd_old_path.startswith('a/'):- cmd_old_path = cmd_old_path[2:]-- if cmd_new_path.startswith('b/'):- cmd_new_path = cmd_new_path[2:]-- return header(- index_path=None,- # wow, I kind of hate this:- # assume /dev/null if the versions are zeroed out- old_path='/dev/null' if old_version == '0000000' else cmd_old_path,- old_version=old_version,- new_path='/dev/null' if new_version == '0000000' else cmd_new_path,- new_version=new_version,- )-- return None---def parse_svn_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- headers = findall_regex(lines, svn_header_index)- if len(headers) == 0:- return None-- while len(lines) > 0:- i = svn_header_index.match(lines[0])- del lines[0]- if not i:- continue-- diff_header = parse_diff_header(lines)- if not diff_header:- return header(- index_path=i.group(1),- old_path=i.group(1),- old_version=None,- new_path=i.group(1),- new_version=None,- )-- opath = diff_header.old_path- over = diff_header.old_version- if over:- oend = svn_header_timestamp_version.match(over)- if oend and oend.group(1):- over = int(oend.group(1))- elif opath:- ts = svn_header_timestamp.match(opath)- if ts:- opath = opath[: -len(ts.group(1))]- oend = svn_header_timestamp_version.match(ts.group(1))- if oend and oend.group(1):- over = int(oend.group(1))-- npath = diff_header.new_path- nver = diff_header.new_version- if nver:- nend = svn_header_timestamp_version.match(diff_header.new_version)- if nend and nend.group(1):- nver = int(nend.group(1))- elif npath:- ts = svn_header_timestamp.match(npath)- if ts:- npath = npath[: -len(ts.group(1))]- nend = svn_header_timestamp_version.match(ts.group(1))- if nend and nend.group(1):- nver = int(nend.group(1))-- if not isinstance(over, int):- over = None-- if not isinstance(nver, int):- nver = None-- return header(- index_path=i.group(1),- old_path=opath,- old_version=over,- new_path=npath,- new_version=nver,- )-- return None---def parse_cvs_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- headers = findall_regex(lines, cvs_header_rcs)- headers_old = findall_regex(lines, old_cvs_diffcmd_header)-- if headers:- # parse rcs style headers- while len(lines) > 0:- i = cvs_header_index.match(lines[0])- del lines[0]- if not i:- continue-- diff_header = parse_diff_header(lines)- if diff_header:- over = diff_header.old_version- if over:- oend = cvs_header_timestamp.match(over)- oend_c = cvs_header_timestamp_colon.match(over)- if oend:- over = oend.group(2)- elif oend_c:- over = oend_c.group(1)-- nver = diff_header.new_version- if nver:- nend = cvs_header_timestamp.match(nver)- nend_c = cvs_header_timestamp_colon.match(nver)- if nend:- nver = nend.group(2)- elif nend_c:- nver = nend_c.group(1)-- return header(- index_path=i.group(1),- old_path=diff_header.old_path,- old_version=over,- new_path=diff_header.new_path,- new_version=nver,- )- return header(- index_path=i.group(1),- old_path=i.group(1),- old_version=None,- new_path=i.group(1),- new_version=None,- )- elif headers_old:- # parse old style headers- while len(lines) > 0:- i = cvs_header_index.match(lines[0])- del lines[0]- if not i:- continue-- d = old_cvs_diffcmd_header.match(lines[0])- if not d:- return header(- index_path=i.group(1),- old_path=i.group(1),- old_version=None,- new_path=i.group(1),- new_version=None,- )-- # will get rid of the useless stuff for us- parse_diff_header(lines)- over = d.group(2) if d.group(2) else None- nver = d.group(4) if d.group(4) else None- return header(- index_path=i.group(1),- old_path=d.group(1),- old_version=over,- new_path=d.group(3),- new_version=nver,- )-- return None---def parse_diffcmd_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- headers = findall_regex(lines, diffcmd_header)- if len(headers) == 0:- return None-- while len(lines) > 0:- d = diffcmd_header.match(lines[0])- del lines[0]- if d:- return header(- index_path=None,- old_path=d.group(1),- old_version=None,- new_path=d.group(2),- new_version=None,- )- return None---def parse_unified_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- headers = findall_regex(lines, unified_header_new_line)- if len(headers) == 0:- return None-- while len(lines) > 1:- o = unified_header_old_line.match(lines[0])- del lines[0]- if o:- n = unified_header_new_line.match(lines[0])- del lines[0]- if n:- over = o.group(2)- if len(over) == 0:- over = None-- nver = n.group(2)- if len(nver) == 0:- nver = None-- return header(- index_path=None,- old_path=o.group(1),- old_version=over,- new_path=n.group(1),- new_version=nver,- )-- return None---def parse_context_header(text: str | list[str]) -> header | None:- lines = text.splitlines() if isinstance(text, str) else text-- headers = findall_regex(lines, context_header_old_line)- if len(headers) == 0:- return None-- while len(lines) > 1:- o = context_header_old_line.match(lines[0])- del lines[0]- if o:- n = context_header_new_line.match(lines[0])- del lines[0]- if n:- over = o.group(2)- if len(over) == 0:- over = None-- nver = n.group(2)- if len(nver) == 0:- nver = None-- return header(- index_path=None,- old_path=o.group(1),- old_version=over,- new_path=n.group(1),- new_version=nver,- )-- return None---def parse_default_diff(text: str | list[str]) -> list[Change] | None:- lines = text.splitlines() if isinstance(text, str) else text-- old = 0- new = 0- old_len = 0- new_len = 0- r = 0- i = 0-- changes = list()-- hunks = split_by_regex(lines, default_hunk_start)- for hunk_n, hunk in enumerate(hunks):- if not len(hunk):- continue-- r = 0- i = 0- while len(hunk) > 0:- h = default_hunk_start.match(hunk[0])- c = default_change.match(hunk[0])- del hunk[0]- if h:- old = int(h.group(1))- if len(h.group(2)) > 0:- old_len = int(h.group(2)) - old + 1- else:- old_len = 0-- new = int(h.group(4))- if len(h.group(5)) > 0:- new_len = int(h.group(5)) - new + 1- else:- new_len = 0-- elif c:- kind = c.group(1)- line = c.group(2)-- if kind == '<' and (r != old_len or r == 0):- changes.append(Change(old + r, None, line, hunk_n))- r += 1- elif kind == '>' and (i != new_len or i == 0):- changes.append(Change(None, new + i, line, hunk_n))- i += 1-- if len(changes) > 0:- return changes-- return None---def parse_unified_diff(text: str | list[str]) -> list[Change] | None:- lines = text.splitlines() if isinstance(text, str) else text-- old = 0- new = 0- r = 0- i = 0- old_len = 0- new_len = 0-- changes = list()-- hunks = split_by_regex(lines, unified_hunk_start)- for hunk_n, hunk in enumerate(hunks):- # reset counters- r = 0- i = 0- while len(hunk) > 0:- h = unified_hunk_start.match(hunk[0])- del hunk[0]- if h:- # The hunk header @@ -1,6 +1,6 @@ means:- # - Start at line 1 in the old file and show 6 lines- # - Start at line 1 in the new file and show 6 lines- old = int(h.group(1)) # Starting line in old file- old_len = (- int(h.group(2)) if len(h.group(2)) > 0 else 1- ) # Number of lines in old file-- new = int(h.group(3)) # Starting line in new file- new_len = (- int(h.group(4)) if len(h.group(4)) > 0 else 1- ) # Number of lines in new file-- h = None- break-- # Process each line in the hunk- for n in hunk:- # Each line in a unified diff starts with a space (context), + (addition), or - (deletion)- # The first character is the kind, the rest is the line content- kind = (- n[0] if len(n) > 0 else ' '- ) # Empty lines in the hunk are treated as context lines- line = n[1:] if len(n) > 1 else ''-- # Process the line based on its kind- if kind == '-' and (r != old_len or r == 0):- # Line was removed from the old file- changes.append(Change(old + r, None, line, hunk_n))- r += 1- elif kind == '+' and (i != new_len or i == 0):- # Line was added in the new file- changes.append(Change(None, new + i, line, hunk_n))- i += 1- elif kind == ' ':- # Context line - exists in both old and new file- changes.append(Change(old + r, new + i, line, hunk_n))- r += 1- i += 1-- if len(changes) > 0:- return changes-- return None---def parse_context_diff(text: str | list[str]) -> list[Change] | None:- lines = text.splitlines() if isinstance(text, str) else text-- old = 0- new = 0- j = 0- k = 0-- changes = list()-- hunks = split_by_regex(lines, context_hunk_start)- for hunk_n, hunk in enumerate(hunks):- if not len(hunk):- continue-- j = 0- k = 0- parts = split_by_regex(hunk, context_hunk_new)- if len(parts) != 2:- raise exceptions.ParseException('Context diff invalid', hunk_n)-- old_hunk = parts[0]- new_hunk = parts[1]-- while len(old_hunk) > 0:- o = context_hunk_old.match(old_hunk[0])- del old_hunk[0]-- if not o:- continue-- old = int(o.group(1))- old_len = int(o.group(2)) + 1 - old- while len(new_hunk) > 0:- n = context_hunk_new.match(new_hunk[0])- del new_hunk[0]-- if not n:- continue-- new = int(n.group(1))- new_len = int(n.group(2)) + 1 - new- break- break-- # now have old and new set, can start processing?- if len(old_hunk) > 0 and len(new_hunk) == 0:- msg = 'Got unexpected change in removal hunk: '- # only removes left?- while len(old_hunk) > 0:- c = context_change.match(old_hunk[0])- del old_hunk[0]-- if not c:- continue-- kind = c.group(1)- line = c.group(2)-- if kind == '-' and (j != old_len or j == 0):- changes.append(Change(old + j, None, line, hunk_n))- j += 1- elif kind == ' ' and (- (j != old_len and k != new_len) or (j == 0 or k == 0)- ):- changes.append(Change(old + j, new + k, line, hunk_n))- j += 1- k += 1- elif kind == '+' or kind == '!':- raise exceptions.ParseException(msg + kind, hunk_n)-- continue-- if len(old_hunk) == 0 and len(new_hunk) > 0:- msg = 'Got unexpected change in removal hunk: '- # only insertions left?- while len(new_hunk) > 0:- c = context_change.match(new_hunk[0])- del new_hunk[0]-- if not c:- continue-- kind = c.group(1)- line = c.group(2)-- if kind == '+' and (k != new_len or k == 0):- changes.append(Change(None, new + k, line, hunk_n))- k += 1- elif kind == ' ' and (- (j != old_len and k != new_len) or (j == 0 or k == 0)- ):- changes.append(Change(old + j, new + k, line, hunk_n))- j += 1- k += 1- elif kind == '-' or kind == '!':- raise exceptions.ParseException(msg + kind, hunk_n)- continue-- # both- while len(old_hunk) > 0 and len(new_hunk) > 0:- oc = context_change.match(old_hunk[0])- nc = context_change.match(new_hunk[0])- okind = None- nkind = None-- if oc:- okind = oc.group(1)- oline = oc.group(2)-- if nc:- nkind = nc.group(1)- nline = nc.group(2)-- if not (oc or nc):- del old_hunk[0]- del new_hunk[0]- elif okind == ' ' and nkind == ' ' and oline == nline:- changes.append(Change(old + j, new + k, oline, hunk_n))- j += 1- k += 1- del old_hunk[0]- del new_hunk[0]- elif okind == '-' or okind == '!' and (j != old_len or j == 0):- changes.append(Change(old + j, None, oline, hunk_n))- j += 1- del old_hunk[0]- elif nkind == '+' or nkind == '!' and (k != new_len or k == 0):- changes.append(Change(None, new + k, nline, hunk_n))- k += 1- del new_hunk[0]- else:- return None-- if len(changes) > 0:- return changes-- return None---def parse_ed_diff(text: str | list[str]) -> list[Change] | None:- lines = text.splitlines() if isinstance(text, str) else text-- old = 0- j = 0- k = 0-- r = 0- i = 0-- changes = list()-- hunks = split_by_regex(lines, ed_hunk_start)- hunks.reverse()- for hunk_n, hunk in enumerate(hunks):- if not len(hunk):- continue- j = 0- k = 0- while len(hunk) > 0:- o = ed_hunk_start.match(hunk[0])- del hunk[0]-- if not o:- continue-- old = int(o.group(1))- old_end = int(o.group(2)) if len(o.group(2)) else old-- hunk_kind = o.group(3)- if hunk_kind == 'd':- k = 0- while old_end >= old:- changes.append(Change(old + k, None, None, hunk_n))- r += 1- k += 1- old_end -= 1- continue-- while len(hunk) > 0:- e = ed_hunk_end.match(hunk[0])- if not e and hunk_kind == 'c':- k = 0- while old_end >= old:- changes.append(Change(old + k, None, None, hunk_n))- r += 1- k += 1- old_end -= 1-- # I basically have no idea why this works- # for these tests.- changes.append(- Change(- None,- old - r + i + k + j,- hunk[0],- hunk_n,- )- )- i += 1- j += 1- if not e and hunk_kind == 'a':- changes.append(- Change(- None,- old - r + i + 1,- hunk[0],- hunk_n,- )- )- i += 1-- del hunk[0]-- if len(changes) > 0:- return changes-- return None---def parse_rcs_ed_diff(text: str | list[str]) -> list[Change] | None:- # much like forward ed, but no 'c' type- lines = text.splitlines() if isinstance(text, str) else text-- old = 0- j = 0- size = 0- total_change_size = 0-- changes = list()-- hunks = split_by_regex(lines, rcs_ed_hunk_start)- for hunk_n, hunk in enumerate(hunks):- if len(hunk):- j = 0- while len(hunk) > 0:- o = rcs_ed_hunk_start.match(hunk[0])- del hunk[0]-- if not o:- continue-- hunk_kind = o.group(1)- old = int(o.group(2))- size = int(o.group(3)) if o.group(3) else 0-- if hunk_kind == 'a':- old += total_change_size + 1- total_change_size += size- while size > 0 and len(hunk) > 0:- changes.append(Change(None, old + j, hunk[0], hunk_n))- j += 1- size -= 1-- del hunk[0]-- elif hunk_kind == 'd':- total_change_size -= size- while size > 0:- changes.append(Change(old + j, None, None, hunk_n))- j += 1- size -= 1-- if len(changes) > 0:- return changes- return None---def parse_git_binary_diff(text: str | list[str]) -> list[Change] | None:- lines = text.splitlines() if isinstance(text, str) else text-- changes: list[Change] = list()-- old_version = None- new_version = None- cmd_old_path = None- cmd_new_path = None- # the sizes are used as latch-up- new_size = 0- old_size = 0- old_encoded = ''- new_encoded = ''- for line in lines:- if cmd_old_path is None and cmd_new_path is None:- hm = git_diffcmd_header.match(line)- if hm:- cmd_old_path = hm.group(1)- cmd_new_path = hm.group(2)- continue-- if old_version is None and new_version is None:- g = git_header_index.match(line)- if g:- old_version = g.group(1)- new_version = g.group(2)- continue-- # the first is added file- if new_size == 0:- literal = git_binary_literal_start.match(line)- if literal:- new_size = int(literal.group(1))- continue- delta = git_binary_delta_start.match(line)- if delta:- # not supported- new_size = 0- continue- elif new_size > 0:- if base85string.match(line):- assert len(line) >= 6 and ((len(line) - 1) % 5) == 0- new_encoded += line[1:]- elif 0 == len(line):- if new_encoded:- decoded = base64.b85decode(new_encoded)- added_data = zlib.decompress(decoded)- assert new_size == len(added_data)- change = Change(None, 0, added_data, None)- changes.append(change)- new_size = 0- new_encoded = ''- else:- # Invalid line format- new_size = 0- new_encoded = ''-- # the second is removed file- if old_size == 0:- literal = git_binary_literal_start.match(line)- if literal:- old_size = int(literal.group(1))- delta = git_binary_delta_start.match(line)- if delta:- # not supported- old_size = 0- continue- elif old_size > 0:- if base85string.match(line):- assert len(line) >= 6 and ((len(line) - 1) % 5) == 0- old_encoded += line[1:]- elif 0 == len(line):- if old_encoded:- decoded = base64.b85decode(old_encoded)- removed_data = zlib.decompress(decoded)- assert old_size == len(removed_data)- change = Change(0, None, None, removed_data)- changes.append(change)- old_size = 0- old_encoded = ''- else:- # Invalid line format- old_size = 0- old_encoded = ''-- return changesdiff --git a/openhands/resolver/patching/snippets.py b/openhands/resolver/patching/snippets.pydeleted file mode 100644index 9272a6f115..0000000000--- a/openhands/resolver/patching/snippets.py+++ /dev/null@@ -1,71 +0,0 @@-# -*- coding: utf-8 -*---# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import os-import re-from shutil import rmtree---def remove(path: str) -> None:- if os.path.exists(path):- if os.path.isdir(path):- rmtree(path)- else:- os.remove(path)---# find all indices of a list of strings that match a regex-def findall_regex(items: list[str], regex: re.Pattern[str]) -> list[int]:- found = list()- for i in range(0, len(items)):- k = regex.match(items[i])- if k:- found.append(i)- k = None-- return found---def split_by_regex(items: list[str], regex: re.Pattern[str]) -> list[list[str]]:- splits = list()- indices = findall_regex(items, regex)- if not indices:- splits.append(items)- return splits-- # Add first chunk before first match- splits.append(items[0 : indices[0]])-- # Add chunks between matches- for i in range(len(indices) - 1):- splits.append(items[indices[i] : indices[i + 1]])-- # Add final chunk after last match- splits.append(items[indices[-1] :])-- return splits---# http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python-def which(program: str) -> str | None:- def is_exe(fpath: str) -> bool:- return os.path.isfile(fpath) and os.access(fpath, os.X_OK)-- fpath, fname = os.path.split(program)- if fpath:- if is_exe(program):- return program- else:- for path in os.environ['PATH'].split(os.pathsep):- path = path.strip('"')- exe_file = os.path.join(path, program)- if is_exe(exe_file):- return exe_file-- return Nonediff --git a/openhands/resolver/prompts/guess_success/issue-success-check.jinja b/openhands/resolver/prompts/guess_success/issue-success-check.jinjadeleted file mode 100644index cfc8e36854..0000000000--- a/openhands/resolver/prompts/guess_success/issue-success-check.jinja+++ /dev/null@@ -1,21 +0,0 @@-Given the following issue description and the last message from an AI agent attempting to fix it, determine if the issue has been successfully resolved based on the changes made and their expected impact. Make your own judgment based on the evidence provided - do NOT defer to or wait for human review.--Issue description:-{{ issue_context }}--Changes made (git patch):-{{ git_patch }}--Last message from AI agent:-{{ last_message }}--(1) Based on the changes made and their expected impact, has the issue been successfully resolved?-(2) Provide a clear explanation of what was done in the PR and whether it addresses the issue. Focus on the concrete changes and their expected effects, not on the need for external verification.--Answer in exactly the format below, with only true or false for success, and an explanation of the result that focuses on the actual changes and their impact.----- success-true/false----- explanation-...diff --git a/openhands/resolver/prompts/guess_success/pr-feedback-check.jinja b/openhands/resolver/prompts/guess_success/pr-feedback-check.jinjadeleted file mode 100644index af7be5cfcd..0000000000--- a/openhands/resolver/prompts/guess_success/pr-feedback-check.jinja+++ /dev/null@@ -1,27 +0,0 @@-You are given one or more issue descriptions, a piece of feedback to resolve the issues, and the last message from an AI agent attempting to incorporate the feedback. If the feedback is addressed to a specific code file, then the file locations will be provided as well. Based on the changes made and their expected impact, determine if the feedback has been successfully resolved. Make your own judgment based on the evidence provided - do NOT defer to or wait for human review.--Issue descriptions:-{{ issue_context }}--Feedback:-{{ feedback }}--Files locations:-{{ files_context }}--Changes made (git patch):-{{ git_patch }}--Last message from AI agent:-{{ last_message }}--(1) Based on the changes made and their expected impact, has the feedback been successfully incorporated?-(2) Provide a clear explanation of what was done and whether it addresses the feedback. Focus on the concrete changes and their expected effects, not on the need for external verification.--Answer in exactly the format below, with only true or false for success, and an explanation that focuses on the actual changes and their impact.----- success-true/false----- explanation-...diff --git a/openhands/resolver/prompts/guess_success/pr-review-check.jinja b/openhands/resolver/prompts/guess_success/pr-review-check.jinjadeleted file mode 100644index 0820d68f52..0000000000--- a/openhands/resolver/prompts/guess_success/pr-review-check.jinja+++ /dev/null@@ -1,24 +0,0 @@-You are given one or more issue descriptions, the PR review comments, and the last message from an AI agent attempting to address the feedback. Based on the changes made and their expected impact, determine if the feedback has been successfully resolved. Make your own judgment based on the evidence provided - do NOT defer to or wait for human review.--Issue descriptions:-{{ issue_context }}--PR Review Comments:-{{ review_context }}--Changes made (git patch):-{{ git_patch }}--Last message from AI agent:-{{ last_message }}--(1) Based on the changes made and their expected impact, has the feedback been successfully incorporated?-(2) Provide a clear explanation of what was done and whether it addresses the feedback. Focus on the concrete changes and their expected effects, not on the need for external verification.--Answer in exactly the format below, with only true or false for success, and an explanation that focuses on the actual changes and their impact.----- success-true/false----- explanation-...diff --git a/openhands/resolver/prompts/guess_success/pr-thread-check.jinja b/openhands/resolver/prompts/guess_success/pr-thread-check.jinjadeleted file mode 100644index 7c483c2b0e..0000000000--- a/openhands/resolver/prompts/guess_success/pr-thread-check.jinja+++ /dev/null@@ -1,24 +0,0 @@-You are given one or more issue descriptions, the PR thread comments, and the last message from an AI agent attempting to address the feedback. Based on the changes made and their expected impact, determine if the feedback has been successfully resolved. Make your own judgment based on the evidence provided - do NOT defer to or wait for human review.--Issue descriptions:-{{ issue_context }}--PR Thread Comments:-{{ thread_context }}--Changes made (git patch):-{{ git_patch }}--Last message from AI agent:-{{ last_message }}--(1) Based on the changes made and their expected impact, has the feedback been successfully incorporated?-(2) Provide a clear explanation of what was done and whether it addresses the feedback. Focus on the concrete changes and their expected effects, not on the need for external verification.--Answer in exactly the format below, with only true or false for success, and an explanation that focuses on the actual changes and their impact.----- success-true/false----- explanation-...diff --git a/openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands-resolver.txt b/openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands-resolver.txtdeleted file mode 100644index e4bc3b165d..0000000000--- a/openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands-resolver.txt+++ /dev/null@@ -1,4 +0,0 @@-This is a Python repo for openhands-resolver, a library that attempts to resolve github issues with the AI agent OpenHands.--- Setup: `poetry install --with test --with dev`-- Testing: `poetry run pytest tests/test_*.py`diff --git a/openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands.txt b/openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands.txtdeleted file mode 100644index 015ea101a0..0000000000--- a/openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands.txt+++ /dev/null@@ -1,7 +0,0 @@-OpenHands is an automated AI software engineer. It is a repo with a Python backend-(in the `openhands` directory) and typescript frontend (in the `frontend` directory).--- Setup: To set up the repo, including frontend/backend you can `make build`-- Backend Testing: All tests are in `tests/unit/test_*.py`. To test new code, you- can do `poetry run pytest tests/unit/test_xxx.py` where `xxx` is the appropriate- file for the current functionality. Write all tests with pytest.diff --git a/openhands/resolver/prompts/repo_instructions/rbren___rss-parser.txt b/openhands/resolver/prompts/repo_instructions/rbren___rss-parser.txtdeleted file mode 100644index 5ef52d64c3..0000000000--- a/openhands/resolver/prompts/repo_instructions/rbren___rss-parser.txt+++ /dev/null@@ -1,4 +0,0 @@-This is a node repo for an RSS parser.-- Setup: `yes | npm install`-- Testing: `SKIP_BROWSER_TESTS=1 npm test`-- Writing Tests: Add to the `test` directory.diff --git a/openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja b/openhands/resolver/prompts/resolve/basic-conversation-instructions.jinjadeleted file mode 100644index 02e20f2da2..0000000000--- a/openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja+++ /dev/null@@ -1,7 +0,0 @@-IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.-You SHOULD INCLUDE PROPER INDENTATION in your edit commands.{% if repo_instruction %}--Some basic information about this repository:-{{ repo_instruction }}{% endif %}--When you think you have fixed the issue through code changes, please finish the interaction.diff --git a/openhands/resolver/prompts/resolve/basic-followup-conversation-instructions.jinja b/openhands/resolver/prompts/resolve/basic-followup-conversation-instructions.jinjadeleted file mode 100644index 8f15a01545..0000000000--- a/openhands/resolver/prompts/resolve/basic-followup-conversation-instructions.jinja+++ /dev/null@@ -1,16 +0,0 @@-The current code is an attempt at fixing one or more issues. The code is not satisfactory and follow up feedback have been provided to address this.-The feedback may be addressed to specific code files. In this case the file locations will be provided.-Please update the code based on the feedback for the repository in /workspace.-An environment has been set up for you to start working. You may assume all necessary tools are installed.--# Issues addressed-{{ issues }}---IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.-You SHOULD INCLUDE PROPER INDENTATION in your edit commands.{% if repo_instruction %}--Some basic information about this repository:-{{ repo_instruction }}{% endif %}--When you think you have fixed the issue through code changes, please finish the interaction.diff --git a/openhands/resolver/prompts/resolve/basic-followup.jinja b/openhands/resolver/prompts/resolve/basic-followup.jinjadeleted file mode 100644index c696a88b52..0000000000--- a/openhands/resolver/prompts/resolve/basic-followup.jinja+++ /dev/null@@ -1,13 +0,0 @@-Please fix the code based on the following feedback--# Review comments-{{ review_comments }}--# Review threads-{{ review_threads }}--# Review thread files-{{ files }}--# PR Thread Comments-{{ thread_context }}diff --git a/openhands/resolver/prompts/resolve/basic-with-tests-conversation-instructions.jinja b/openhands/resolver/prompts/resolve/basic-with-tests-conversation-instructions.jinjadeleted file mode 100644index 86a89397bc..0000000000--- a/openhands/resolver/prompts/resolve/basic-with-tests-conversation-instructions.jinja+++ /dev/null@@ -1,11 +0,0 @@-IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.-You SHOULD INCLUDE PROPER INDENTATION in your edit commands.{% if repo_instruction %}--Some basic information about this repository:-{{ repo_instruction }}{% endif %}--For all changes to actual application code (e.g. in Python or Javascript), add an appropriate test to the testing directory to make sure that the issue has been fixed.-Run the tests, and if they pass you are done!-You do NOT need to write new tests if there are only changes to documentation or configuration files.--When you think you have fixed the issue through code changes, please call the finish action to end the interaction.diff --git a/openhands/resolver/prompts/resolve/basic-with-tests.jinja b/openhands/resolver/prompts/resolve/basic-with-tests.jinjadeleted file mode 100644index fbe444ab4a..0000000000--- a/openhands/resolver/prompts/resolve/basic-with-tests.jinja+++ /dev/null@@ -1,5 +0,0 @@-Please fix the following issue for the repository in /workspace.-An environment has been set up for you to start working. You may assume all necessary tools are installed.--# Problem Statement-{{ body }}diff --git a/openhands/resolver/prompts/resolve/basic.jinja b/openhands/resolver/prompts/resolve/basic.jinjadeleted file mode 100644index fbe444ab4a..0000000000--- a/openhands/resolver/prompts/resolve/basic.jinja+++ /dev/null@@ -1,5 +0,0 @@-Please fix the following issue for the repository in /workspace.-An environment has been set up for you to start working. You may assume all necessary tools are installed.--# Problem Statement-{{ body }}diff --git a/openhands/resolver/prompts/resolve/pr-changes-summary.jinja b/openhands/resolver/prompts/resolve/pr-changes-summary.jinjadeleted file mode 100644index ba9b1bcab4..0000000000--- a/openhands/resolver/prompts/resolve/pr-changes-summary.jinja+++ /dev/null@@ -1,3 +0,0 @@-Please create a concise overview of the following changes, commenting on whether all issues have been successfully resolved or if there are still issues remaining:--{{ comment_message }}diff --git a/openhands/resolver/resolve_issue.py b/openhands/resolver/resolve_issue.pydeleted file mode 100644index a13ae2866d..0000000000--- a/openhands/resolver/resolve_issue.py+++ /dev/null@@ -1,142 +0,0 @@-# flake8: noqa: E501--# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import asyncio--from openhands.resolver.issue_resolver import IssueResolver---def main() -> None:- import argparse-- def int_or_none(value: str) -> int | None:- if value.lower() == 'none':- return None- else:- return int(value)-- parser = argparse.ArgumentParser(description='Resolve a single issue.')- parser.add_argument(- '--selected-repo',- type=str,- required=True,- help='repository to resolve issues in form of `owner/repo`.',- )- parser.add_argument(- '--token',- type=str,- default=None,- help='token to access the repository.',- )- parser.add_argument(- '--username',- type=str,- default=None,- help='username to access the repository.',- )- parser.add_argument(- '--base-container-image',- type=str,- default=None,- help='base container image to use.',- )- parser.add_argument(- '--runtime-container-image',- type=str,- default=None,- help='Container image to use.',- )- parser.add_argument(- '--runtime',- type=str,- default=None,- help='Runtime environment to use (default: docker).',- )- parser.add_argument(- '--max-iterations',- type=int,- default=50,- help='Maximum number of iterations to run.',- )- parser.add_argument(- '--issue-number',- type=int,- required=True,- help='Issue number to resolve.',- )- parser.add_argument(- '--comment-id',- type=int_or_none,- required=False,- default=None,- help='Resolve a specific comment',- )- parser.add_argument(- '--output-dir',- type=str,- default='output',- help='Output directory to write the results.',- )- parser.add_argument(- '--llm-model',- type=str,- default=None,- help='LLM model to use.',- )- parser.add_argument(- '--llm-api-key',- type=str,- default=None,- help='LLM API key to use.',- )- parser.add_argument(- '--llm-base-url',- type=str,- default=None,- help='LLM base URL to use.',- )- parser.add_argument(- '--prompt-file',- type=str,- default=None,- help='Path to the prompt template file in Jinja format.',- )- parser.add_argument(- '--repo-instruction-file',- type=str,- default=None,- help='Path to the repository instruction file in text format.',- )- parser.add_argument(- '--issue-type',- type=str,- default='issue',- choices=['issue', 'pr'],- help='Type of issue to resolve, either open issue or pr comments.',- )- parser.add_argument(- '--is-experimental',- type=lambda x: x.lower() == 'true',- help='Whether to run in experimental mode.',- )- parser.add_argument(- '--base-domain',- type=str,- default=None,- help='Base domain for the git server (defaults to "github.com" for GitHub, "gitlab.com" for GitLab, "bitbucket.org" for Bitbucket, and "dev.azure.com" for Azure DevOps)',- )-- my_args = parser.parse_args()-- issue_resolver = IssueResolver(my_args)- asyncio.run(issue_resolver.resolve_issue())---if __name__ == '__main__':- main()diff --git a/openhands/resolver/resolver_output.py b/openhands/resolver/resolver_output.pydeleted file mode 100644index 5f853711ad..0000000000--- a/openhands/resolver/resolver_output.py+++ /dev/null@@ -1,27 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from typing import Any--from litellm import BaseModel--from openhands.resolver.interfaces.issue import Issue---class ResolverOutput(BaseModel):- # NOTE: User-specified- issue: Issue- issue_type: str- instruction: str- base_commit: str- git_patch: str- history: list[dict[str, Any]]- metrics: dict[str, Any] | None- success: bool- comment_success: list[bool] | None- result_explanation: str- error: str | Nonediff --git a/openhands/resolver/send_pull_request.py b/openhands/resolver/send_pull_request.pydeleted file mode 100644index d2ffc7f8a8..0000000000--- a/openhands/resolver/send_pull_request.py+++ /dev/null@@ -1,876 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import argparse-import json-import os-import shutil-import subprocess--import jinja2-from pydantic import SecretStr--from openhands.core.config import LLMConfig-from openhands.core.logger import openhands_logger as logger-from openhands.integrations.service_types import ProviderType-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.azure_devops import AzureDevOpsIssueHandler-from openhands.resolver.interfaces.bitbucket import BitbucketIssueHandler-from openhands.resolver.interfaces.bitbucket_data_center import BitbucketDCIssueHandler-from openhands.resolver.interfaces.forgejo import ForgejoIssueHandler-from openhands.resolver.interfaces.github import GithubIssueHandler-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.interfaces.issue_definitions import ServiceContextIssue-from openhands.resolver.io_utils import (- load_single_resolver_output,-)-from openhands.resolver.patching import apply_diff, parse_patch-from openhands.resolver.resolver_output import ResolverOutput-from openhands.resolver.utils import identify_token-from openhands.utils.async_utils import GENERAL_TIMEOUT, call_async_from_sync-from openhands.utils.environment import get_effective_llm_base_url--PR_SIGNATURE = (- 'Automatic fix generated by [OpenHands](https://github.com/OpenHands/OpenHands/) π'-)---def apply_patch(repo_dir: str, patch: str) -> None:- """Apply a patch to a repository.-- Args:- repo_dir: The directory containing the repository- patch: The patch to apply- """- diffs = parse_patch(patch)- for diff in diffs:- if not diff.header.new_path:- logger.warning('Could not determine file to patch')- continue-- # Remove both "a/" and "b/" prefixes from paths- old_path = (- os.path.join(- repo_dir, diff.header.old_path.removeprefix('a/').removeprefix('b/')- )- if diff.header.old_path and diff.header.old_path != '/dev/null'- else None- )- new_path = os.path.join(- repo_dir, diff.header.new_path.removeprefix('a/').removeprefix('b/')- )-- # Check if the file is being deleted- if diff.header.new_path == '/dev/null':- assert old_path is not None- if os.path.exists(old_path):- os.remove(old_path)- logger.info(f'Deleted file: {old_path}')- continue-- # Handle file rename- if old_path and new_path and 'rename from' in diff.text:- # Create parent directory of new path- os.makedirs(os.path.dirname(new_path), exist_ok=True)- try:- # Try to move the file directly- shutil.move(old_path, new_path)- except shutil.SameFileError:- # If it's the same file (can happen with directory renames), copy first then remove- shutil.copy2(old_path, new_path)- os.remove(old_path)-- # Try to remove empty parent directories- old_dir = os.path.dirname(old_path)- while old_dir and old_dir.startswith(repo_dir):- try:- os.rmdir(old_dir)- old_dir = os.path.dirname(old_dir)- except OSError:- # Directory not empty or other error, stop trying to remove parents- break- continue-- if old_path:- # Open the file in binary mode to detect line endings- with open(old_path, 'rb') as f:- original_content = f.read()-- # Detect line endings- if b'\r\n' in original_content:- newline = '\r\n'- elif b'\n' in original_content:- newline = '\n'- else:- newline = None # Let Python decide-- try:- with open(old_path, 'r', newline=newline) as f:- split_content = [x.strip(newline) for x in f.readlines()]- except UnicodeDecodeError as e:- logger.error(f'Error reading file {old_path}: {e}')- split_content = []- else:- newline = '\n'- split_content = []-- if diff.changes is None:- logger.warning(f'No changes to apply for {old_path}')- continue-- new_content = apply_diff(diff, split_content)-- # Ensure the directory exists before writing the file- os.makedirs(os.path.dirname(new_path), exist_ok=True)-- # Write the new content using the detected line endings- with open(new_path, 'w', newline=newline) as f:- for line in new_content:- print(line, file=f)-- logger.info('Patch applied successfully')---def initialize_repo(- output_dir: str, issue_number: int, issue_type: str, base_commit: str | None = None-) -> str:- """Initialize the repository.-- Args:- output_dir: The output directory to write the repository to- issue_number: The issue number to fix- issue_type: The type of the issue- base_commit: The base commit to checkout (if issue_type is pr)- """- src_dir = os.path.join(output_dir, 'repo')- dest_dir = os.path.join(output_dir, 'patches', f'{issue_type}_{issue_number}')-- if not os.path.exists(src_dir):- raise ValueError(f'Source directory {src_dir} does not exist.')-- if os.path.exists(dest_dir):- shutil.rmtree(dest_dir)-- shutil.copytree(src_dir, dest_dir)- logger.info(f'Copied repository to {dest_dir}')-- # Checkout the base commit if provided- if base_commit:- result = subprocess.run(- f'git -C {dest_dir} checkout {base_commit}',- shell=True,- capture_output=True,- text=True,- )- if result.returncode != 0:- logger.info(f'Error checking out commit: {result.stderr}')- raise RuntimeError('Failed to check out commit')-- return dest_dir---def make_commit(- repo_dir: str,- issue: Issue,- issue_type: str,- git_user_name: str = 'openhands',- git_user_email: str = '[email protected]',-) -> None:- """Make a commit with the changes to the repository.-- Args:- repo_dir: The directory containing the repository- issue: The issue to fix- issue_type: The type of the issue- git_user_name: Git username for commits- git_user_email: Git email for commits- """- # Check if git username is set- result = subprocess.run(- f'git -C {repo_dir} config user.name',- shell=True,- capture_output=True,- text=True,- )-- if not result.stdout.strip():- # If username is not set, configure git with the provided credentials- subprocess.run(- f'git -C {repo_dir} config user.name "{git_user_name}" && '- f'git -C {repo_dir} config user.email "{git_user_email}" && '- f'git -C {repo_dir} config alias.git "git --no-pager"',- shell=True,- check=True,- )- logger.info(f'Git user configured as {git_user_name} <{git_user_email}>')-- # Add all changes to the git index- result = subprocess.run(- f'git -C {repo_dir} add .', shell=True, capture_output=True, text=True- )- if result.returncode != 0:- logger.error(f'Error adding files: {result.stderr}')- raise RuntimeError('Failed to add files to git')-- # Check the status of the git index- status_result = subprocess.run(- f'git -C {repo_dir} status --porcelain',- shell=True,- capture_output=True,- text=True,- )-- # If there are no changes, raise an error- if not status_result.stdout.strip():- logger.error(- f'No changes to commit for issue #{issue.number}. Skipping commit.'- )- raise RuntimeError('ERROR: Openhands failed to make code changes.')-- # Prepare the commit message- commit_message = f'Fix {issue_type} #{issue.number}: {issue.title}'-- # Commit the changes- result = subprocess.run(- ['git', '-C', repo_dir, 'commit', '-m', commit_message],- capture_output=True,- text=True,- )- if result.returncode != 0:- raise RuntimeError(f'Failed to commit changes: {result}')---def send_pull_request(- issue: Issue,- token: str,- username: str | None,- platform: ProviderType,- patch_dir: str,- pr_type: str,- fork_owner: str | None = None,- additional_message: str | None = None,- target_branch: str | None = None,- reviewer: str | None = None,- pr_title: str | None = None,- base_domain: str | None = None,- git_user_name: str = 'openhands',- git_user_email: str = '[email protected]',-) -> str:- """Send a pull request to a GitHub, GitLab, Bitbucket, Forgejo, or Azure DevOps repository.-- Args:- issue: The issue to send the pull request for- token: The token to use for authentication- username: The username, if provided- platform: The platform of the repository.- patch_dir: The directory containing the patches to apply- pr_type: The type: branch (no PR created), draft or ready (regular PR created)- fork_owner: The owner of the fork to push changes to (if different from the original repo owner)- additional_message: The additional messages to post as a comment on the PR in json list format- target_branch: The target branch to create the pull request against (defaults to repository default branch)- reviewer: The username of the reviewer to assign- pr_title: Custom title for the pull request (optional)- base_domain: The base domain for the git server (defaults to "github.com" for GitHub, "gitlab.com" for GitLab, "bitbucket.org" for Bitbucket, "codeberg.org" for Forgejo, and "dev.azure.com" for Azure DevOps)- git_user_name: Git username to configure when creating commits- git_user_email: Git email to configure when creating commits- """- if pr_type not in ['branch', 'draft', 'ready']:- raise ValueError(f'Invalid pr_type: {pr_type}')-- # Determine default base_domain based on platform- if base_domain is None:- base_domain = {- ProviderType.GITHUB: 'github.com',- ProviderType.GITLAB: 'gitlab.com',- ProviderType.BITBUCKET: 'bitbucket.org',- ProviderType.FORGEJO: 'codeberg.org',- ProviderType.AZURE_DEVOPS: 'dev.azure.com',- }.get(platform, 'github.com')-- # Create the appropriate handler based on platform- handler = None- if platform == ProviderType.GITHUB:- handler = ServiceContextIssue(- GithubIssueHandler(issue.owner, issue.repo, token, username, base_domain),- None,- )- elif platform == ProviderType.GITLAB:- handler = ServiceContextIssue(- GitlabIssueHandler(issue.owner, issue.repo, token, username, base_domain),- None,- )- elif platform == ProviderType.BITBUCKET:- handler = ServiceContextIssue(- BitbucketIssueHandler(- issue.owner, issue.repo, token, username, base_domain- ),- None,- )- elif platform == ProviderType.BITBUCKET_DATA_CENTER:- handler = ServiceContextIssue(- BitbucketDCIssueHandler(- issue.owner, issue.repo, token, username, base_domain- ),- None,- )- elif platform == ProviderType.FORGEJO:- handler = ServiceContextIssue(- ForgejoIssueHandler(issue.owner, issue.repo, token, username, base_domain),- None,- )- elif platform == ProviderType.AZURE_DEVOPS:- # For Azure DevOps, owner is "organization/project"- organization, project = issue.owner.split('/')- handler = ServiceContextIssue(- AzureDevOpsIssueHandler(token, organization, project, issue.repo),- None,- )- else:- raise ValueError(f'Unsupported platform: {platform}')-- # Create a new branch with a unique name- base_branch_name = f'openhands-fix-issue-{issue.number}'- branch_name = handler.get_branch_name(- base_branch_name=base_branch_name,- )-- # Get the default branch or use specified target branch- logger.info('Getting base branch...')- if target_branch:- base_branch = target_branch- exists = handler.branch_exists(branch_name=target_branch)- if not exists:- raise ValueError(f'Target branch {target_branch} does not exist')- else:- base_branch = handler.get_default_branch_name()- logger.info(f'Base branch: {base_branch}')-- # Create and checkout the new branch- logger.info('Creating new branch...')- result = subprocess.run(- ['git', '-C', patch_dir, 'checkout', '-b', branch_name],- capture_output=True,- text=True,- )- if result.returncode != 0:- logger.error(f'Error creating new branch: {result.stderr}')- raise RuntimeError(- f'Failed to create a new branch {branch_name} in {patch_dir}:'- )-- # Determine the repository to push to (original or fork)- push_owner = fork_owner if fork_owner else issue.owner-- handler._strategy.set_owner(push_owner)-- logger.info('Pushing changes...')- push_url = handler.get_clone_url()- result = subprocess.run(- ['git', '-C', patch_dir, 'push', push_url, branch_name],- capture_output=True,- text=True,- )- if result.returncode != 0:- logger.error(f'Error pushing changes: {result.stderr}')- raise RuntimeError('Failed to push changes to the remote repository')-- # Prepare the PR data: title and body- final_pr_title = (- pr_title if pr_title else f'Fix issue #{issue.number}: {issue.title}'- )- pr_body = f'This pull request fixes #{issue.number}.'- if additional_message:- pr_body += f'\n\n{additional_message}'- pr_body += f'\n\n{PR_SIGNATURE}'-- # For cross repo pull request, we need to send head parameter like fork_owner:branch as per git documentation here : https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#create-a-pull-request- # head parameter usage : The name of the branch where your changes are implemented. For cross-repository pull requests in the same network, namespace head with a user like this: username:branch.- if fork_owner and platform in (ProviderType.GITHUB, ProviderType.FORGEJO):- head_branch = f'{fork_owner}:{branch_name}'- else:- head_branch = branch_name- # If we are not sending a PR, we can finish early and return the- # URL for the user to open a PR manually- if pr_type == 'branch':- url = handler.get_compare_url(branch_name)- else:- # Prepare the PR for the GitHub API- if platform == ProviderType.GITHUB:- data = {- 'title': final_pr_title,- 'body': pr_body,- 'head': head_branch,- 'base': base_branch,- 'draft': pr_type == 'draft',- }- elif platform == ProviderType.GITLAB:- data = {- 'title': final_pr_title,- 'description': pr_body,- 'source_branch': head_branch,- 'target_branch': base_branch,- 'draft': pr_type == 'draft',- }- elif platform == ProviderType.BITBUCKET:- data = {- 'title': final_pr_title,- 'description': pr_body,- 'source_branch': head_branch,- 'target_branch': base_branch,- 'draft': pr_type == 'draft',- }- elif platform == ProviderType.BITBUCKET_DATA_CENTER:- data = {- 'title': final_pr_title,- 'description': pr_body,- 'source_branch': head_branch,- 'target_branch': base_branch,- 'draft': pr_type == 'draft',- }- elif platform == ProviderType.FORGEJO:- data = {- 'title': final_pr_title,- 'body': pr_body,- 'head': head_branch,- 'base': base_branch,- 'draft': pr_type == 'draft',- }- else:- raise ValueError(f'Unsupported platform for PR creation: {platform}')-- pr_data = handler.create_pull_request(data)- url = pr_data['html_url']-- # Request review if a reviewer was specified- if reviewer and pr_type != 'branch':- number = pr_data['number']- handler.request_reviewers(reviewer, number)-- logger.info(- f'{pr_type} created: {url}\n\n--- Title: {final_pr_title}\n\n--- Body:\n{pr_body}'- )-- return url---def update_existing_pull_request(- issue: Issue,- token: str,- username: str | None,- platform: ProviderType,- patch_dir: str,- llm_config: LLMConfig,- comment_message: str | None = None,- additional_message: str | None = None,- base_domain: str | None = None,-) -> str:- """Update an existing pull request with the new patches.-- Args:- issue: The issue to update.- token: The token to use for authentication.- username: The username to use for authentication.- platform: The platform of the repository.- patch_dir: The directory containing the patches to apply.- llm_config: The LLM configuration to use for summarizing changes.- comment_message: The main message to post as a comment on the PR.- additional_message: The additional messages to post as a comment on the PR in json list format.- base_domain: The base domain for the git server (defaults to "github.com" for GitHub, "gitlab.com" for GitLab, and "dev.azure.com" for Azure DevOps)- """- # Set up headers and base URL for GitHub or GitLab API-- # Determine default base_domain based on platform- if base_domain is None:- base_domain = {- ProviderType.GITHUB: 'github.com',- ProviderType.GITLAB: 'gitlab.com',- ProviderType.AZURE_DEVOPS: 'dev.azure.com',- ProviderType.BITBUCKET: 'bitbucket.org',- ProviderType.FORGEJO: 'codeberg.org',- ProviderType.BITBUCKET_DATA_CENTER: 'bitbucket.example.com',- }.get(platform, 'github.com')-- handler = None- if platform == ProviderType.GITHUB:- handler = ServiceContextIssue(- GithubIssueHandler(issue.owner, issue.repo, token, username, base_domain),- llm_config,- )- elif platform == ProviderType.GITLAB:- handler = ServiceContextIssue(- GitlabIssueHandler(issue.owner, issue.repo, token, username, base_domain),- llm_config,- )- elif platform == ProviderType.AZURE_DEVOPS:- # For Azure DevOps, owner is "organization/project"- organization, project = issue.owner.split('/')- handler = ServiceContextIssue(- AzureDevOpsIssueHandler(token, organization, project, issue.repo),- llm_config,- )- elif platform == ProviderType.BITBUCKET:- handler = ServiceContextIssue(- BitbucketIssueHandler(- issue.owner, issue.repo, token, username, base_domain- ),- llm_config,- )- elif platform == ProviderType.BITBUCKET_DATA_CENTER:- handler = ServiceContextIssue(- BitbucketDCIssueHandler(- issue.owner, issue.repo, token, username, base_domain- ),- llm_config,- )- elif platform == ProviderType.FORGEJO:- handler = ServiceContextIssue(- ForgejoIssueHandler(issue.owner, issue.repo, token, username, base_domain),- llm_config,- )- else:- raise ValueError(f'Unsupported platform: {platform}')-- branch_name = issue.head_branch-- # Prepare the push command- push_command = (- f'git -C {patch_dir} push '- f'{handler.get_authorize_url()}'- f'{issue.owner}/{issue.repo}.git {branch_name}'- )-- # Push the changes to the existing branch- result = subprocess.run(push_command, shell=True, capture_output=True, text=True)- if result.returncode != 0:- logger.error(f'Error pushing changes: {result.stderr}')- raise RuntimeError('Failed to push changes to the remote repository')-- pr_url = handler.get_pull_url(issue.number)- logger.info(f'Updated pull request {pr_url} with new patches.')-- # Generate a summary of all comment success indicators for PR message- if not comment_message and additional_message:- try:- explanations = json.loads(additional_message)- if explanations:- comment_message = (- 'OpenHands made the following changes to resolve the issues:\n\n'- )- for explanation in explanations:- comment_message += f'- {explanation}\n'-- # Summarize with LLM if provided- if llm_config is not None:- llm = LLM(llm_config, service_id='resolver')- with open(- os.path.join(- os.path.dirname(__file__),- 'prompts/resolve/pr-changes-summary.jinja',- ),- 'r',- ) as f:- template = jinja2.Template(f.read())- prompt = template.render(comment_message=comment_message)- response = llm.completion(- messages=[{'role': 'user', 'content': prompt}],- )- comment_message = response.choices[0].message.content.strip()-- except (json.JSONDecodeError, TypeError):- comment_message = (- 'A new OpenHands update is available, but failed to parse or summarize '- f'the changes:\n{additional_message}'- )-- # Post a comment on the PR- if comment_message:- handler.send_comment_msg(issue.number, comment_message)-- # Reply to each unresolved comment thread- if additional_message and issue.thread_ids:- try:- explanations = json.loads(additional_message)- for count, reply_comment in enumerate(explanations):- comment_id = issue.thread_ids[count]- handler.reply_to_comment(issue.number, comment_id, reply_comment)- except (json.JSONDecodeError, TypeError):- msg = f'Error occurred when replying to threads; success explanations {additional_message}'- handler.send_comment_msg(issue.number, msg)-- return pr_url---def process_single_issue(- output_dir: str,- resolver_output: ResolverOutput,- token: str,- username: str,- platform: ProviderType,- pr_type: str,- llm_config: LLMConfig,- fork_owner: str | None,- send_on_failure: bool,- target_branch: str | None = None,- reviewer: str | None = None,- pr_title: str | None = None,- base_domain: str | None = None,- git_user_name: str = 'openhands',- git_user_email: str = '[email protected]',-) -> None:- # Determine default base_domain based on platform- if base_domain is None:- base_domain = (- 'github.com'- if platform == ProviderType.GITHUB- else 'gitlab.com'- if platform == ProviderType.GITLAB- else 'dev.azure.com'- if platform == ProviderType.AZURE_DEVOPS- else 'bitbucket.org'- if platform == ProviderType.BITBUCKET- else 'bitbucket.example.com'- if platform == ProviderType.BITBUCKET_DATA_CENTER- else 'github.com'- )- if not resolver_output.success and not send_on_failure:- logger.info(- f'Issue {resolver_output.issue.number} was not successfully resolved. Skipping PR creation.'- )- return-- issue_type = resolver_output.issue_type-- if issue_type == 'issue':- patched_repo_dir = initialize_repo(- output_dir,- resolver_output.issue.number,- issue_type,- resolver_output.base_commit,- )- elif issue_type == 'pr':- patched_repo_dir = initialize_repo(- output_dir,- resolver_output.issue.number,- issue_type,- resolver_output.issue.head_branch,- )- else:- raise ValueError(f'Invalid issue type: {issue_type}')-- apply_patch(patched_repo_dir, resolver_output.git_patch)-- make_commit(- patched_repo_dir,- resolver_output.issue,- issue_type,- git_user_name,- git_user_email,- )-- if issue_type == 'pr':- update_existing_pull_request(- issue=resolver_output.issue,- token=token,- username=username,- platform=platform,- patch_dir=patched_repo_dir,- additional_message=resolver_output.result_explanation,- llm_config=llm_config,- base_domain=base_domain,- )- else:- send_pull_request(- issue=resolver_output.issue,- token=token,- username=username,- platform=platform,- patch_dir=patched_repo_dir,- pr_type=pr_type,- fork_owner=fork_owner,- additional_message=resolver_output.result_explanation,- target_branch=target_branch,- reviewer=reviewer,- pr_title=pr_title,- base_domain=base_domain,- git_user_name=git_user_name,- git_user_email=git_user_email,- )---def main() -> None:- parser = argparse.ArgumentParser(- description='Send a pull request to Github, Gitlab, or Azure DevOps.'- )- parser.add_argument(- '--selected-repo',- type=str,- default=None,- help='repository to send pull request in form of `owner/repo`.',- )- parser.add_argument(- '--token',- type=str,- default=None,- help='token to access the repository.',- )- parser.add_argument(- '--username',- type=str,- default=None,- help='username to access the repository.',- )- parser.add_argument(- '--output-dir',- type=str,- default='output',- help='Output directory to write the results.',- )- parser.add_argument(- '--pr-type',- type=str,- default='draft',- choices=['branch', 'draft', 'ready'],- help='Type of the pull request to send [branch, draft, ready]',- )- parser.add_argument(- '--issue-number',- type=str,- required=True,- help="Issue number to send the pull request for, or 'all_successful' to process all successful issues.",- )- parser.add_argument(- '--fork-owner',- type=str,- default=None,- help='Owner of the fork to push changes to (if different from the original repo owner).',- )- parser.add_argument(- '--send-on-failure',- action='store_true',- help='Send a pull request even if the issue was not successfully resolved.',- )- parser.add_argument(- '--llm-model',- type=str,- default=None,- help='LLM model to use for summarizing changes.',- )- parser.add_argument(- '--llm-api-key',- type=str,- default=None,- help='API key for the LLM model.',- )- parser.add_argument(- '--llm-base-url',- type=str,- default=None,- help='Base URL for the LLM model.',- )- parser.add_argument(- '--target-branch',- type=str,- default=None,- help='Target branch to create the pull request against (defaults to repository default branch)',- )- parser.add_argument(- '--reviewer',- type=str,- help='GitHub, GitLab, or Azure DevOps username of the person to request review from',- default=None,- )- parser.add_argument(- '--pr-title',- type=str,- help='Custom title for the pull request',- default=None,- )- parser.add_argument(- '--base-domain',- type=str,- default=None,- help='Base domain for the git server (defaults to "github.com" for GitHub, "gitlab.com" for GitLab, and "dev.azure.com" for Azure DevOps)',- )- parser.add_argument(- '--git-user-name',- type=str,- default='openhands',- help='Git user name for commits',- )- parser.add_argument(- '--git-user-email',- type=str,- default='[email protected]',- help='Git user email for commits',- )- my_args = parser.parse_args()-- token = (- my_args.token- or os.getenv('GITHUB_TOKEN')- or os.getenv('GITLAB_TOKEN')- or os.getenv('AZURE_DEVOPS_TOKEN')- or os.getenv('FORGEJO_TOKEN')- )- if not token:- raise ValueError(- 'token is not set, set via --token or GITHUB_TOKEN, GITLAB_TOKEN, AZURE_DEVOPS_TOKEN, or FORGEJO_TOKEN environment variable.'- )- username = my_args.username if my_args.username else os.getenv('GIT_USERNAME')-- platform = call_async_from_sync(- identify_token,- GENERAL_TIMEOUT,- token,- my_args.base_domain,- )-- api_key = my_args.llm_api_key or os.environ['LLM_API_KEY']- model_name = my_args.llm_model or os.environ['LLM_MODEL']- base_url = my_args.llm_base_url or os.environ.get('LLM_BASE_URL')- resolved_base_url = get_effective_llm_base_url(- model_name,- base_url,- )- llm_config = LLMConfig(- model=model_name,- api_key=SecretStr(api_key) if api_key else None,- base_url=resolved_base_url,- )-- if not os.path.exists(my_args.output_dir):- raise ValueError(f'Output directory {my_args.output_dir} does not exist.')-- if not my_args.issue_number.isdigit():- raise ValueError(f'Issue number {my_args.issue_number} is not a number.')- issue_number = int(my_args.issue_number)- output_path = os.path.join(my_args.output_dir, 'output.jsonl')- resolver_output = load_single_resolver_output(output_path, issue_number)- if not username:- raise ValueError('username is required.')- process_single_issue(- my_args.output_dir,- resolver_output,- token,- username,- platform,- my_args.pr_type,- llm_config,- my_args.fork_owner,- my_args.send_on_failure,- my_args.target_branch,- my_args.reviewer,- my_args.pr_title,- my_args.base_domain,- my_args.git_user_name,- my_args.git_user_email,- )---if __name__ == '__main__':- main()diff --git a/openhands/resolver/utils.py b/openhands/resolver/utils.pydeleted file mode 100644index 62475da897..0000000000--- a/openhands/resolver/utils.py+++ /dev/null@@ -1,168 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import logging-import multiprocessing as mp-import os-import re-from typing import Callable--from pydantic import SecretStr--from openhands.controller.state.state import State-from openhands.core.logger import get_console_handler-from openhands.core.logger import openhands_logger as logger-from openhands.events.action import Action-from openhands.events.action.message import MessageAction-from openhands.integrations.service_types import ProviderType-from openhands.integrations.utils import validate_provider_token---async def identify_token(token: str, base_domain: str | None) -> ProviderType:- """Identifies whether a token belongs to GitHub, GitLab, Bitbucket, or Azure DevOps.- Parameters:- token (str): The personal access token to check.- base_domain (str): Custom base domain for provider (e.g GitHub Enterprise)- """- provider = await validate_provider_token(SecretStr(token), base_domain)- if not provider:- raise ValueError('Token is invalid.')-- return provider---def codeact_user_response(- state: State,- encapsulate_solution: bool = False,- try_parse: Callable[[Action | None], str] | None = None,-) -> str:- encaps_str = (- (- 'Please encapsulate your final answer (answer ONLY) within <solution> and </solution>.\n'- 'For example: The answer to the question is <solution> 42 </solution>.\n'- )- if encapsulate_solution- else ''- )- msg = (- 'Please continue working on the task on whatever approach you think is suitable.\n'- 'If you think you have solved the task, please first send your answer to user through message and then finish the interaction.\n'- f'{encaps_str}'- 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP.\n'- )-- if state.history:- # check if the last action has an answer, if so, early exit- if try_parse is not None:- last_action = next(- (- event- for event in reversed(state.history)- if isinstance(event, Action)- ),- None,- )- ans = try_parse(last_action)- if ans is not None:- return '/exit'-- # check if the agent has tried to talk to the user 3 times, if so, let the agent know it can give up- user_msgs = [- event- for event in state.history- if isinstance(event, MessageAction) and event.source == 'user'- ]- if len(user_msgs) >= 2:- # let the agent know that it can give up when it has tried 3 times- return (- msg- + 'If you want to give up, run: <execute_bash> exit </execute_bash>.\n'- )- return msg---def cleanup() -> None:- logger.info('Cleaning up child processes...')- for process in mp.active_children():- logger.info(f'Terminating child process: {process.name}')- process.terminate()- process.join()---def reset_logger_for_multiprocessing(- logger: logging.Logger, instance_id: str, log_dir: str-) -> None:- """Reset the logger for multiprocessing.-- Save logs to a separate file for each process, instead of trying to write to the- same file/console from multiple processes.- """- # Set up logger- log_file = os.path.join(- log_dir,- f'instance_{instance_id}.log',- )- # Remove all existing handlers from logger- for handler in logger.handlers[:]:- logger.removeHandler(handler)- # add back the console handler to print ONE line- logger.addHandler(get_console_handler())- logger.info(- f'Starting resolver for instance {instance_id}.\n'- f'Hint: run "tail -f {log_file}" to see live logs in a separate shell'- )- # Remove all existing handlers from logger- for handler in logger.handlers[:]:- logger.removeHandler(handler)- os.makedirs(os.path.dirname(log_file), exist_ok=True)- file_handler = logging.FileHandler(log_file)- file_handler.setFormatter(- logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')- )- logger.addHandler(file_handler)---def extract_image_urls(issue_body: str) -> list[str]:- # Regular expression to match Markdown image syntax - image_pattern = r'!\[.*?\]\((https?://[^\s)]+)\)'- return re.findall(image_pattern, issue_body)---def extract_issue_references(body: str) -> list[int]:- # First, remove code blocks as they may contain false positives- body = re.sub(r'```.*?```', '', body, flags=re.DOTALL)-- # Remove inline code- body = re.sub(r'`[^`]*`', '', body)-- # Remove URLs that contain hash symbols- body = re.sub(r'https?://[^\s)]*#\d+[^\s)]*', '', body)-- # Now extract issue numbers, making sure they're not part of other text- # The pattern matches #number that:- # 1. Is at the start of text or after whitespace/punctuation- # 2. Is followed by whitespace, punctuation, or end of text- # 3. Is not part of a URL- pattern = r'(?:^|[\s\[({]|[^\w#])#(\d+)(?=[\s,.\])}]|$)'- return [int(match) for match in re.findall(pattern, body)]---def get_unique_uid(start_uid: int = 1000) -> int:- existing_uids = set()- with open('/etc/passwd', 'r') as passwd_file:- for line in passwd_file:- parts = line.split(':')- if len(parts) > 2:- try:- existing_uids.add(int(parts[2]))- except ValueError:- continue-- while start_uid in existing_uids:- start_uid += 1-- return start_uiddiff --git a/openhands/resolver/visualize_resolver_output.py b/openhands/resolver/visualize_resolver_output.pydeleted file mode 100644index c0c954ffed..0000000000--- a/openhands/resolver/visualize_resolver_output.py+++ /dev/null@@ -1,52 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import argparse-import os--from openhands.resolver.io_utils import load_single_resolver_output---def visualize_resolver_output(- issue_number: int, output_dir: str, vis_method: str-) -> None:- output_jsonl = os.path.join(output_dir, 'output.jsonl')- resolver_output = load_single_resolver_output(output_jsonl, issue_number)- if vis_method == 'json':- print(resolver_output.model_dump_json(indent=4))- else:- raise ValueError(f'Invalid visualization method: {vis_method}')---if __name__ == '__main__':- parser = argparse.ArgumentParser(description='Visualize a patch.')- parser.add_argument(- '--issue-number',- type=int,- required=True,- help='Issue number to send the pull request for.',- )- parser.add_argument(- '--output-dir',- type=str,- default='output',- help='Output directory to write the results.',- )- parser.add_argument(- '--vis-method',- type=str,- default='json',- choices=['json'],- help='Method to visualize the patch [json].',- )- my_args = parser.parse_args()-- visualize_resolver_output(- issue_number=my_args.issue_number,- output_dir=my_args.output_dir,- vis_method=my_args.vis_method,- )diff --git a/tests/unit/integrations/bitbucket/test_bitbucket.py b/tests/unit/integrations/bitbucket/test_bitbucket.pyindex a205ed31e5..1debbb2220 100644--- a/tests/unit/integrations/bitbucket/test_bitbucket.py+++ b/tests/unit/integrations/bitbucket/test_bitbucket.py@@ -13,224 +13,11 @@ from openhands.integrations.provider import ProviderToken, ProviderTypefrom openhands.integrations.service_types import OwnerType, Repositoryfrom openhands.integrations.service_types import ProviderType as ServiceProviderTypefrom openhands.integrations.utils import validate_provider_token-from openhands.resolver.interfaces.bitbucket import BitbucketIssueHandler-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.interfaces.issue_definitions import ServiceContextIssue-from openhands.resolver.send_pull_request import PR_SIGNATURE, send_pull_requestfrom openhands.runtime.base import Runtimefrom openhands.server.settings import POSTProviderModelfrom openhands.server.types import AppMode-# BitbucketIssueHandler Tests-def bitbucket_handler():- return BitbucketIssueHandler(- owner='test-workspace',- repo='test-repo',- token='test-token',- username='test-user',- )---def test_init():- handler = BitbucketIssueHandler(- owner='test-workspace',- repo='test-repo',- token='test-token',- username='test-user',- )-- assert handler.owner == 'test-workspace'- assert handler.repo == 'test-repo'- assert handler.token == 'test-token'- assert handler.username == 'test-user'- assert handler.base_domain == 'bitbucket.org'- assert handler.base_url == 'https://api.bitbucket.org/2.0'- assert (- handler.download_url- == 'https://bitbucket.org/test-workspace/test-repo/get/master.zip'- )- assert handler.clone_url == 'https://bitbucket.org/test-workspace/test-repo.git'- assert handler.headers == {- 'Authorization': 'Bearer test-token',- 'Accept': 'application/json',- }---def test_get_repo_url(bitbucket_handler):- assert (- bitbucket_handler.get_repo_url()- == 'https://bitbucket.org/test-workspace/test-repo'- )---def test_get_issue_url(bitbucket_handler):- assert (- bitbucket_handler.get_issue_url(123)- == 'https://bitbucket.org/test-workspace/test-repo/issues/123'- )---def test_get_pr_url(bitbucket_handler):- assert (- bitbucket_handler.get_pr_url(123)- == 'https://bitbucket.org/test-workspace/test-repo/pull-requests/123'- )---@patch('httpx.AsyncClient')-async def test_get_issue(mock_client, bitbucket_handler):- mock_response = MagicMock()- mock_response.raise_for_status = AsyncMock()- mock_response.json.return_value = {- 'id': 123,- 'title': 'Test Issue',- 'content': {'raw': 'Test Issue Body'},- 'links': {- 'html': {- 'href': 'https://bitbucket.org/test-workspace/test-repo/issues/123'- }- },- 'state': 'open',- 'reporter': {'display_name': 'Test User'},- 'assignee': [{'display_name': 'Assignee User'}],- }-- mock_client_instance = AsyncMock()- mock_client_instance.get.return_value = mock_response- mock_client.return_value.__aenter__.return_value = mock_client_instance-- issue = await bitbucket_handler.get_issue(123)-- assert issue.number == 123- assert issue.title == 'Test Issue'- assert issue.body == 'Test Issue Body'- # We don't test for html_url, state, user, or assignees as they're not part of the Issue model---@patch('httpx.post')-def test_create_pr(mock_post, bitbucket_handler):- mock_response = MagicMock()- mock_response.raise_for_status.return_value = None- mock_response.json.return_value = {- 'links': {- 'html': {- 'href': 'https://bitbucket.org/test-workspace/test-repo/pull-requests/123'- }- },- }- mock_post.return_value = mock_response-- pr_url = bitbucket_handler.create_pr(- title='Test PR',- body='Test PR Body',- head='feature-branch',- base='main',- )-- assert pr_url == 'https://bitbucket.org/test-workspace/test-repo/pull-requests/123'-- expected_payload = {- 'title': 'Test PR',- 'description': 'Test PR Body',- 'source': {'branch': {'name': 'feature-branch'}},- 'destination': {'branch': {'name': 'main'}},- 'close_source_branch': False,- }-- mock_post.assert_called_once_with(- 'https://api.bitbucket.org/2.0/repositories/test-workspace/test-repo/pullrequests',- headers=bitbucket_handler.headers,- json=expected_payload,- )---# Bitbucket Send Pull Request Tests-@patch('openhands.resolver.send_pull_request.ServiceContextIssue')-@patch('openhands.resolver.send_pull_request.BitbucketIssueHandler')-@patch('subprocess.run')-def test_send_pull_request_bitbucket(- mock_run, mock_bitbucket_handler, mock_service_context-):- # Mock subprocess.run to avoid actual git operations- mock_run.return_value = MagicMock(returncode=0)-- # Mock the BitbucketIssueHandler instance- mock_instance = MagicMock(spec=BitbucketIssueHandler)- mock_bitbucket_handler.return_value = mock_instance-- # Mock the ServiceContextIssue instance- mock_service = MagicMock(spec=ServiceContextIssue)- mock_service.get_branch_name.return_value = 'openhands-fix-123'- mock_service.branch_exists.return_value = True- mock_service.get_default_branch_name.return_value = 'main'- mock_service.get_clone_url.return_value = (- 'https://bitbucket.org/test-workspace/test-repo.git'- )- mock_service.create_pull_request.return_value = {- 'html_url': 'https://bitbucket.org/test-workspace/test-repo/pull-requests/123'- }- # Add _strategy attribute to mock- mock_strategy = MagicMock()- mock_service._strategy = mock_strategy- mock_service_context.return_value = mock_service-- # Create a mock Issue- mock_issue = Issue(- number=123,- title='Test Issue',- owner='test-workspace',- repo='test-repo',- body='Test body',- created_at='2023-01-01T00:00:00Z',- updated_at='2023-01-01T00:00:00Z',- closed_at=None,- head_branch='feature-branch',- thread_ids=None,- )-- # Call send_pull_request- result = send_pull_request(- issue=mock_issue,- token='test-token',- username=None,- platform=ServiceProviderType.BITBUCKET,- patch_dir='/tmp', # Use /tmp instead of /tmp/repo to avoid directory not found error- pr_type='ready',- pr_title='Test PR',- target_branch='main',- )-- # Verify the result- assert result == 'https://bitbucket.org/test-workspace/test-repo/pull-requests/123'-- # Verify the handler was created correctly- mock_bitbucket_handler.assert_called_once_with(- 'test-workspace',- 'test-repo',- 'test-token',- None,- 'bitbucket.org',- )-- # Verify ServiceContextIssue was created correctly- mock_service_context.assert_called_once()-- # Verify create_pull_request was called with the correct data- expected_body = f'This pull request fixes #123.\n\n{PR_SIGNATURE}'- mock_service.create_pull_request.assert_called_once_with(- {- 'title': 'Test PR',- 'description': expected_body,- 'source_branch': 'openhands-fix-123',- 'target_branch': 'main',- 'draft': False,- }- )--# Bitbucket Provider Domain Testsclass TestBitbucketProviderDomain(unittest.TestCase):"""Test that Bitbucket provider domain is properly handled in Runtime.clone_or_init_repo."""diff --git a/tests/unit/integrations/forgejo/test_forgejo_send_pull_request.py b/tests/unit/integrations/forgejo/test_forgejo_send_pull_request.pydeleted file mode 100644index f697f07b19..0000000000--- a/tests/unit/integrations/forgejo/test_forgejo_send_pull_request.py+++ /dev/null@@ -1,78 +0,0 @@-"""Tests for Forgejo integration with send_pull_request."""--from unittest.mock import MagicMock, patch--from openhands.integrations.service_types import ProviderType as ServiceProviderType-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.send_pull_request import PR_SIGNATURE, send_pull_request---@patch('openhands.resolver.send_pull_request.ServiceContextIssue')-@patch('openhands.resolver.send_pull_request.ForgejoIssueHandler')-@patch('subprocess.run')-def test_send_pull_request_forgejo(- mock_run, mock_forgejo_handler, mock_service_context-):- """Ensure we can build and submit a Forgejo pull request."""- mock_run.return_value = MagicMock(returncode=0)-- handler_instance = MagicMock()- mock_forgejo_handler.return_value = handler_instance-- service_context_instance = MagicMock()- service_context_instance.get_branch_name.return_value = 'openhands-fix-issue-7'- service_context_instance.branch_exists.return_value = True- service_context_instance.get_default_branch_name.return_value = 'main'- service_context_instance.get_clone_url.return_value = (- 'https://codeberg.org/example/repo.git'- )- service_context_instance.create_pull_request.return_value = {- 'html_url': 'https://codeberg.org/example/repo/pulls/42',- 'number': 42,- }- service_context_instance._strategy = MagicMock()- mock_service_context.return_value = service_context_instance-- issue = Issue(- number=7,- title='Fix the Forgejo PR flow',- owner='example',- repo='repo',- body='Details about the fix',- created_at='2024-01-01T00:00:00Z',- updated_at='2024-01-01T00:00:00Z',- closed_at=None,- head_branch='feature-branch',- thread_ids=None,- )-- result = send_pull_request(- issue=issue,- token='forgejo-token',- username=None,- platform=ServiceProviderType.FORGEJO,- patch_dir='/tmp',- pr_type='ready',- pr_title='Fix the Forgejo PR flow',- target_branch='main',- )-- assert result == 'https://codeberg.org/example/repo/pulls/42'-- mock_forgejo_handler.assert_called_once_with(- 'example', 'repo', 'forgejo-token', None, 'codeberg.org'- )- mock_service_context.assert_called_once_with(handler_instance, None)-- expected_payload = {- 'title': 'Fix the Forgejo PR flow',- 'body': f'This pull request fixes #7.\n\n{PR_SIGNATURE}',- 'head': 'openhands-fix-issue-7',- 'base': 'main',- 'draft': False,- }- service_context_instance.create_pull_request.assert_called_once_with(- expected_payload- )-- mock_run.assert_called()diff --git a/tests/unit/resolver/bitbucket_dc/test_bitbucket_dc_issue_handler.py b/tests/unit/resolver/bitbucket_dc/test_bitbucket_dc_issue_handler.pydeleted file mode 100644index 617a0db8f7..0000000000--- a/tests/unit/resolver/bitbucket_dc/test_bitbucket_dc_issue_handler.py+++ /dev/null@@ -1,357 +0,0 @@-import base64-from unittest.mock import AsyncMock, MagicMock, patch--import pytest-from pydantic import SecretStr--from openhands.core.config import LLMConfig-from openhands.integrations.service_types import ProviderType-from openhands.resolver.interfaces.bitbucket_data_center import (- BitbucketDCIssueHandler,- BitbucketDCPRHandler,-)-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)-from openhands.resolver.issue_handler_factory import IssueHandlerFactory---def handler():- return BitbucketDCIssueHandler(- owner='PROJ',- repo='my-repo',- token='user:secret',- base_domain='bitbucket.example.com',- )---def llm_config():- return LLMConfig(model='test-model', api_key=SecretStr('test-key'))---# ----------------------------------------------------------------------------# URL / attribute tests-# ------------------------------------------------------------------------------def test_init_sets_correct_urls(handler):- assert handler.base_url == 'https://bitbucket.example.com/rest/api/1.0'- assert (- handler.download_url- == 'https://bitbucket.example.com/rest/api/latest/projects/PROJ/repos/my-repo/archive?format=zip'- )- assert handler.clone_url == 'https://bitbucket.example.com/scm/proj/my-repo.git'---def test_get_headers_returns_basic_auth(handler):- expected = base64.b64encode(b'user:secret').decode()- headers = handler.get_headers()- assert headers['Authorization'] == f'Basic {expected}'- assert headers['Accept'] == 'application/json'---def test_get_headers_bare_token_with_username():- h = BitbucketDCIssueHandler(- owner='PROJ',- repo='my-repo',- token='mytoken',- username='myuser',- base_domain='dc.example.com',- )- expected = base64.b64encode(b'myuser:mytoken').decode()- assert h.headers['Authorization'] == f'Basic {expected}'---def test_get_repo_url(handler):- assert (- handler.get_repo_url()- == 'https://bitbucket.example.com/projects/PROJ/repos/my-repo'- )---def test_get_issue_url_returns_pr_url(handler):- assert (- handler.get_issue_url(42)- == 'https://bitbucket.example.com/projects/PROJ/repos/my-repo/pull-requests/42'- )---def test_get_branch_url(handler):- assert (- handler.get_branch_url('feature/x')- == 'https://bitbucket.example.com/projects/PROJ/repos/my-repo/browse?at=refs/heads/feature/x'- )---def test_get_authorize_url_with_colon_token(handler):- url = handler.get_authorize_url()- assert url == 'https://user:[email protected]/'---def test_get_authorize_url_with_username_and_bare_token():- h = BitbucketDCIssueHandler(- owner='PROJ',- repo='my-repo',- token='baretoken',- username='john',- base_domain='dc.example.com',- )- assert h.get_authorize_url() == 'https://john:[email protected]/'---# ----------------------------------------------------------------------------# get_compare_url (requires get_default_branch_name)-# ------------------------------------------------------------------------------def test_get_compare_url(handler):- with patch.object(handler, 'get_default_branch_name', return_value='main'):- url = handler.get_compare_url('feature/fix')- assert url == (- 'https://bitbucket.example.com/projects/PROJ/repos/my-repo/compare/commits'- '?sourceBranch=refs/heads/feature/fix&targetBranch=refs/heads/main'- )---# ----------------------------------------------------------------------------# API methods (mock httpx)-# ------------------------------------------------------------------------------async def test_get_issue_fetches_pr_endpoint(handler):- mock_response = MagicMock()- mock_response.json.return_value = {- 'id': 7,- 'title': 'Fix the thing',- 'description': 'Some body',- 'fromRef': {'displayId': 'feature/fix'},- 'toRef': {'displayId': 'main'},- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.get = AsyncMock(return_value=mock_response)- mock_client.__aenter__ = AsyncMock(return_value=mock_client)- mock_client.__aexit__ = AsyncMock(return_value=None)-- with patch('httpx.AsyncClient', return_value=mock_client):- issue = await handler.get_issue(7)-- expected_url = (- 'https://bitbucket.example.com/rest/api/1.0'- '/projects/PROJ/repos/my-repo/pull-requests/7'- )- mock_client.get.assert_called_once_with(expected_url, headers=handler.headers)- assert issue.number == 7- assert issue.title == 'Fix the thing'- assert issue.body == 'Some body'- assert issue.head_branch == 'feature/fix'- assert issue.base_branch == 'main'---def test_create_pr_uses_from_to_ref(handler):- mock_response = MagicMock()- mock_response.json.return_value = {- 'id': 3,- 'links': {- 'self': [- {- 'href': 'https://bitbucket.example.com/projects/PROJ/repos/my-repo/pull-requests/3'- }- ]- },- }- mock_response.raise_for_status = MagicMock()-- with patch('httpx.post', return_value=mock_response) as mock_post:- url = handler.create_pr('Title', 'Body', 'feature/src', 'main')-- _, kwargs = mock_post.call_args- payload = kwargs['json']- assert payload['fromRef']['id'] == 'refs/heads/feature/src'- assert payload['toRef']['id'] == 'refs/heads/main'- assert payload['fromRef']['repository']['slug'] == 'my-repo'- assert payload['fromRef']['repository']['project']['key'] == 'PROJ'- assert (- url- == 'https://bitbucket.example.com/projects/PROJ/repos/my-repo/pull-requests/3'- )---def test_create_pull_request_returns_html_url_and_number(handler):- mock_response = MagicMock()- mock_response.json.return_value = {- 'id': 5,- 'links': {- 'self': [- {- 'href': 'https://bitbucket.example.com/projects/PROJ/repos/my-repo/pull-requests/5'- }- ]- },- }- mock_response.raise_for_status = MagicMock()-- with patch('httpx.post', return_value=mock_response):- result = handler.create_pull_request(- {- 'title': 'My PR',- 'description': 'desc',- 'source_branch': 'feature/x',- 'target_branch': 'main',- }- )-- assert result['number'] == 5- assert result['html_url'] == (- 'https://bitbucket.example.com/projects/PROJ/repos/my-repo/pull-requests/5'- )---def test_send_comment_msg_uses_text_field(handler):- mock_response = MagicMock()- mock_response.raise_for_status = MagicMock()-- with patch('httpx.post', return_value=mock_response) as mock_post:- handler.send_comment_msg(7, 'Hello from OpenHands')-- _, kwargs = mock_post.call_args- assert kwargs['json'] == {'text': 'Hello from OpenHands'}---def test_reply_to_comment_posts_with_parent_id(handler):- mock_response = MagicMock()- mock_response.raise_for_status = MagicMock()-- with patch('httpx.post', return_value=mock_response) as mock_post:- handler.reply_to_comment(7, '42', 'My reply')-- _, kwargs = mock_post.call_args- assert kwargs['json']['text'] == 'My reply'- assert kwargs['json']['parent'] == {'id': 42}---def test_branch_exists_true(handler):- mock_response = MagicMock()- mock_response.json.return_value = {- 'values': [{'displayId': 'feature/fix', 'id': 'refs/heads/feature/fix'}]- }- mock_response.raise_for_status = MagicMock()-- with patch('httpx.get', return_value=mock_response):- assert handler.branch_exists('feature/fix') is True---def test_branch_exists_false(handler):- mock_response = MagicMock()- mock_response.json.return_value = {'values': []}- mock_response.raise_for_status = MagicMock()-- with patch('httpx.get', return_value=mock_response):- assert handler.branch_exists('nonexistent') is False---def test_branch_exists_no_match(handler):- mock_response = MagicMock()- # filterText returns similar but not exact match- mock_response.json.return_value = {- 'values': [{'displayId': 'feature/fix-extended'}]- }- mock_response.raise_for_status = MagicMock()-- with patch('httpx.get', return_value=mock_response):- assert handler.branch_exists('feature/fix') is False---def test_get_default_branch_name_reads_display_id(handler):- mock_response = MagicMock()- mock_response.json.return_value = {- 'defaultBranch': {'displayId': 'main', 'id': 'refs/heads/main'}- }- mock_response.raise_for_status = MagicMock()-- with patch('httpx.get', return_value=mock_response):- assert handler.get_default_branch_name() == 'main'---def test_get_default_branch_name_strips_refs_heads_prefix(handler):- mock_response = MagicMock()- mock_response.json.return_value = {- 'defaultBranch': {'displayId': 'refs/heads/develop'}- }- mock_response.raise_for_status = MagicMock()-- with patch('httpx.get', return_value=mock_response):- assert handler.get_default_branch_name() == 'develop'---def test_get_default_branch_name_fallback_to_master(handler):- import httpx as httpx_module-- with patch('httpx.get', side_effect=httpx_module.HTTPError('connection refused')):- assert handler.get_default_branch_name() == 'master'---def test_get_context_returns_early(handler):- """get_context_from_external_issues_references should return closing_issues without API calls."""- closing_issues = ['issue body 1']- with patch('httpx.get') as mock_get:- result = handler.get_context_from_external_issues_references(- closing_issues=closing_issues,- closing_issue_numbers=[1],- issue_body='some body',- review_comments=None,- review_threads=[],- thread_comments=None,- )- mock_get.assert_not_called()- assert result == ['issue body 1']---def test_download_issues_returns_empty(handler):- result = handler.download_issues()- assert result == []---# ----------------------------------------------------------------------------# Factory integration tests-# ------------------------------------------------------------------------------def test_factory_creates_dc_issue_handler(llm_config):- factory = IssueHandlerFactory(- owner='PROJ',- repo='my-repo',- token='user:secret',- username='user',- platform=ProviderType.BITBUCKET_DATA_CENTER,- base_domain='bitbucket.example.com',- issue_type='issue',- llm_config=llm_config,- )- ctx = factory.create()- assert isinstance(ctx, ServiceContextIssue)- assert isinstance(ctx._strategy, BitbucketDCIssueHandler)- assert ctx._strategy.owner == 'PROJ'- assert ctx._strategy.repo == 'my-repo'- assert ctx._strategy.base_domain == 'bitbucket.example.com'---def test_factory_creates_dc_pr_handler(llm_config):- factory = IssueHandlerFactory(- owner='PROJ',- repo='my-repo',- token='user:secret',- username='user',- platform=ProviderType.BITBUCKET_DATA_CENTER,- base_domain='bitbucket.example.com',- issue_type='pr',- llm_config=llm_config,- )- ctx = factory.create()- assert isinstance(ctx, ServiceContextPR)- assert isinstance(ctx._strategy, BitbucketDCPRHandler)diff --git a/tests/unit/resolver/github/test_guess_success.py b/tests/unit/resolver/github/test_guess_success.pydeleted file mode 100644index bef1e1f49b..0000000000--- a/tests/unit/resolver/github/test_guess_success.py+++ /dev/null@@ -1,202 +0,0 @@-import json-from unittest.mock import MagicMock, patch--from openhands.core.config import LLMConfig-from openhands.events.action.message import MessageAction-from openhands.llm import LLM-from openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandler-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)---def test_guess_success_multiline_explanation():- # Mock data- issue = Issue(- owner='test',- repo='test',- number=1,- title='Test Issue',- body='Test body',- thread_comments=None,- review_comments=None,- )- history = [MessageAction(content='Test message')]- llm_config = LLMConfig(model='test', api_key='test')-- # Create a mock response with multi-line explanation- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The PR successfully addressed the issue by:-- Fixed bug A-- Added test B-- Updated documentation C--Automatic fix generated by OpenHands π"""- )- )- ]-- # Use patch to mock the LLM completion call- with patch.object(LLM, 'completion', return_value=mock_response) as mock_completion:- # Create a handler instance- handler = ServiceContextIssue(- GithubIssueHandler('test', 'test', 'test'), llm_config- )-- # Call guess_success- success, _, explanation = handler.guess_success(issue, history)-- # Verify the results- assert success is True- assert 'The PR successfully addressed the issue by:' in explanation- assert 'Fixed bug A' in explanation- assert 'Added test B' in explanation- assert 'Updated documentation C' in explanation- assert 'Automatic fix generated by OpenHands' in explanation-- # Verify that LLM completion was called exactly once- mock_completion.assert_called_once()---def test_pr_handler_guess_success_with_thread_comments():- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(GithubPRHandler('test', 'test', 'test'), llm_config)-- # Create a mock issue with thread comments but no review comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=['First comment', 'Second comment'],- closing_issues=['Issue description'],- review_comments=None,- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history- history = [MessageAction(content='Fixed the issue by implementing X and Y')]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion', return_value=mock_response):- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the results- assert success is True- assert success_list == [True]- assert 'successfully address' in explanation- assert len(json.loads(explanation)) == 1---def test_pr_handler_guess_success_only_review_comments():- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with only review comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue description'],- review_comments=['Please fix the formatting', 'Add more tests'],- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history- history = [MessageAction(content='Fixed the formatting and added more tests')]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the review comments."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion', return_value=mock_response):- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the results- assert success is True- assert success_list == [True]- assert (- '["The changes successfully address the review comments."]' in explanation- )---def test_pr_handler_guess_success_no_comments():- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(GithubPRHandler('test', 'test', 'test'), llm_config)-- # Create a mock issue with no comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue description'],- review_comments=None,- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history- history = [MessageAction(content='Fixed the issue')]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Test that it returns appropriate message when no comments are present- success, success_list, explanation = handler.guess_success(issue, history)- assert success is False- assert success_list is None- assert explanation == 'No feedback was found to process'diff --git a/tests/unit/resolver/github/test_issue_handler.py b/tests/unit/resolver/github/test_issue_handler.pydeleted file mode 100644index e09351ad70..0000000000--- a/tests/unit/resolver/github/test_issue_handler.py+++ /dev/null@@ -1,645 +0,0 @@-from unittest.mock import MagicMock, patch--from openhands.core.config import LLMConfig-from openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandler-from openhands.resolver.interfaces.issue import ReviewThread-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)---def test_get_converted_issues_initializes_review_comments():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for issues- mock_issues_response = MagicMock()- mock_issues_response.json.return_value = [- {'number': 1, 'title': 'Test Issue', 'body': 'Test Body'}- ]- # Mock the response for comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = []-- # Set up the mock to return different responses for different calls- # First call is for issues, second call is for comments- mock_get.side_effect = [- mock_issues_response,- mock_comments_response,- mock_comments_response,- ] # Need two comment responses because we make two API calls-- # Create an instance of IssueHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GithubIssueHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- issues = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one issue- assert len(issues) == 1-- # Verify that review_comments is initialized as None- assert issues[0].review_comments is None-- # Verify other fields are set correctly- assert issues[0].number == 1- assert issues[0].title == 'Test Issue'- assert issues[0].body == 'Test Body'- assert issues[0].owner == 'test-owner'- assert issues[0].repo == 'test-repo'---def test_get_converted_issues_handles_empty_body():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for issues- mock_issues_response = MagicMock()- mock_issues_response.json.return_value = [- {'number': 1, 'title': 'Test Issue', 'body': None}- ]- # Mock the response for comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = []- # Set up the mock to return different responses- mock_get.side_effect = [- mock_issues_response,- mock_comments_response,- mock_comments_response,- ]-- # Create an instance of IssueHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GithubIssueHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- issues = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one issue- assert len(issues) == 1-- # Verify that body is empty string when None- assert issues[0].body == ''-- # Verify other fields are set correctly- assert issues[0].number == 1- assert issues[0].title == 'Test Issue'- assert issues[0].owner == 'test-owner'- assert issues[0].repo == 'test-repo'-- # Verify that review_comments is initialized as None- assert issues[0].review_comments is None---def test_pr_handler_get_converted_issues_with_comments():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'number': 1,- 'title': 'Test PR',- 'body': 'Test Body fixes #1',- 'head': {'ref': 'test-branch'},- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'body': 'First comment'},- {'body': 'Second comment'},- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'repository': {- 'pullRequest': {- 'closingIssuesReferences': {'edges': []},- 'reviews': {'nodes': []},- 'reviewThreads': {'edges': []},- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- # Mock the response for fetching the external issue referenced in PR body- mock_external_issue_response = MagicMock()- mock_external_issue_response.json.return_value = {- 'body': 'This is additional context from an externally referenced issue.'- }-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_comments_response, # Third call for PR comments- mock_empty_response, # Fourth call for PR comments (empty page)- mock_external_issue_response, # Mock response for the external issue reference #1- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments == ['First comment', 'Second comment']-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body fixes #1'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'- assert prs[0].closing_issues == [- 'This is additional context from an externally referenced issue.'- ]---def test_get_issue_comments_with_specific_comment_id():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'id': 123, 'body': 'First comment'},- {'id': 456, 'body': 'Second comment'},- ]-- mock_get.return_value = mock_comments_response-- # Create an instance of IssueHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GithubIssueHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get comments with a specific comment_id- specific_comment = handler.get_issue_comments(issue_number=1, comment_id=123)-- # Verify only the specific comment is returned- assert specific_comment == ['First comment']---def test_pr_handler_get_converted_issues_with_specific_thread_comment():- # Define the specific comment_id to filter- specific_comment_id = 123-- # Mock GraphQL response for review threads- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'number': 1,- 'title': 'Test PR',- 'body': 'Test Body',- 'head': {'ref': 'test-branch'},- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'body': 'First comment', 'id': 123},- {'body': 'Second comment', 'id': 124},- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'repository': {- 'pullRequest': {- 'closingIssuesReferences': {'edges': []},- 'reviews': {'nodes': []},- 'reviewThreads': {- 'edges': [- {- 'node': {- 'id': 'review-thread-1',- 'isResolved': False,- 'comments': {- 'nodes': [- {- 'fullDatabaseId': 121,- 'body': 'Specific review comment',- 'path': 'file1.txt',- },- {- 'fullDatabaseId': 456,- 'body': 'Another review comment',- 'path': 'file2.txt',- },- ]- },- }- }- ]- },- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_comments_response, # Third call for PR comments- mock_empty_response, # Fourth call for PR comments (empty page)- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments == ['First comment']- assert prs[0].review_comments == []- assert prs[0].review_threads == []-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'---def test_pr_handler_get_converted_issues_with_specific_review_thread_comment():- # Define the specific comment_id to filter- specific_comment_id = 123-- # Mock GraphQL response for review threads- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'number': 1,- 'title': 'Test PR',- 'body': 'Test Body',- 'head': {'ref': 'test-branch'},- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'body': 'First comment', 'id': 120},- {'body': 'Second comment', 'id': 124},- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'repository': {- 'pullRequest': {- 'closingIssuesReferences': {'edges': []},- 'reviews': {'nodes': []},- 'reviewThreads': {- 'edges': [- {- 'node': {- 'id': 'review-thread-1',- 'isResolved': False,- 'comments': {- 'nodes': [- {- 'fullDatabaseId': specific_comment_id,- 'body': 'Specific review comment',- 'path': 'file1.txt',- },- {- 'fullDatabaseId': 456,- 'body': 'Another review comment',- 'path': 'file1.txt',- },- ]- },- }- }- ]- },- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_comments_response, # Third call for PR comments- mock_empty_response, # Fourth call for PR comments (empty page)- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments is None- assert prs[0].review_comments == []- assert len(prs[0].review_threads) == 1- assert isinstance(prs[0].review_threads[0], ReviewThread)- assert (- prs[0].review_threads[0].comment- == 'Specific review comment\n---\nlatest feedback:\nAnother review comment\n'- )- assert prs[0].review_threads[0].files == ['file1.txt']-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'---def test_pr_handler_get_converted_issues_with_specific_comment_and_issue_refs():- # Define the specific comment_id to filter- specific_comment_id = 123-- # Mock GraphQL response for review threads- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'number': 1,- 'title': 'Test PR fixes #3',- 'body': 'Test Body',- 'head': {'ref': 'test-branch'},- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'body': 'First comment', 'id': 120},- {'body': 'Second comment', 'id': 124},- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'repository': {- 'pullRequest': {- 'closingIssuesReferences': {'edges': []},- 'reviews': {'nodes': []},- 'reviewThreads': {- 'edges': [- {- 'node': {- 'id': 'review-thread-1',- 'isResolved': False,- 'comments': {- 'nodes': [- {- 'fullDatabaseId': specific_comment_id,- 'body': 'Specific review comment that references #6',- 'path': 'file1.txt',- },- {- 'fullDatabaseId': 456,- 'body': 'Another review comment referencing #7',- 'path': 'file2.txt',- },- ]- },- }- }- ]- },- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- # Mock the response for fetching the external issue referenced in PR body- mock_external_issue_response_in_body = MagicMock()- mock_external_issue_response_in_body.json.return_value = {- 'body': 'External context #1.'- }-- # Mock the response for fetching the external issue referenced in review thread- mock_external_issue_response_review_thread = MagicMock()- mock_external_issue_response_review_thread.json.return_value = {- 'body': 'External context #2.'- }-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_comments_response, # Third call for PR comments- mock_empty_response, # Fourth call for PR comments (empty page)- mock_external_issue_response_in_body,- mock_external_issue_response_review_thread,- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments is None- assert prs[0].review_comments == []- assert len(prs[0].review_threads) == 1- assert isinstance(prs[0].review_threads[0], ReviewThread)- assert (- prs[0].review_threads[0].comment- == 'Specific review comment that references #6\n---\nlatest feedback:\nAnother review comment referencing #7\n'- )- assert prs[0].closing_issues == [- 'External context #1.',- 'External context #2.',- ] # Only includes references inside comment ID and body PR-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR fixes #3'- assert prs[0].body == 'Test Body'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'---def test_pr_handler_get_converted_issues_with_duplicate_issue_refs():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'number': 1,- 'title': 'Test PR',- 'body': 'Test Body fixes #1',- 'head': {'ref': 'test-branch'},- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'body': 'First comment addressing #1'},- {'body': 'Second comment addressing #2'},- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'repository': {- 'pullRequest': {- 'closingIssuesReferences': {'edges': []},- 'reviews': {'nodes': []},- 'reviewThreads': {'edges': []},- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- # Mock the response for fetching the external issue referenced in PR body- mock_external_issue_response_in_body = MagicMock()- mock_external_issue_response_in_body.json.return_value = {- 'body': 'External context #1.'- }-- # Mock the response for fetching the external issue referenced in review thread- mock_external_issue_response_in_comment = MagicMock()- mock_external_issue_response_in_comment.json.return_value = {- 'body': 'External context #2.'- }-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_comments_response, # Third call for PR comments- mock_empty_response, # Fourth call for PR comments (empty page)- mock_external_issue_response_in_body, # Mock response for the external issue reference #1- mock_external_issue_response_in_comment,- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments == [- 'First comment addressing #1',- 'Second comment addressing #2',- ]-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body fixes #1'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'- assert prs[0].closing_issues == [- 'External context #1.',- 'External context #2.',- ]diff --git a/tests/unit/resolver/github/test_issue_handler_error_handling.py b/tests/unit/resolver/github/test_issue_handler_error_handling.pydeleted file mode 100644index ec58f18f68..0000000000--- a/tests/unit/resolver/github/test_issue_handler_error_handling.py+++ /dev/null@@ -1,278 +0,0 @@-from unittest.mock import MagicMock, patch--import httpx-import pytest-from litellm.exceptions import RateLimitError--from openhands.core.config import LLMConfig-from openhands.events.action.message import MessageAction-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandler-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)--[email protected](autouse=True)-def mock_logger(monkeypatch):- # suppress logging of completion data to file- mock_logger = MagicMock()- monkeypatch.setattr('openhands.llm.debug_mixin.llm_prompt_logger', mock_logger)- monkeypatch.setattr('openhands.llm.debug_mixin.llm_response_logger', mock_logger)- return mock_logger---def default_config():- return LLMConfig(- model='gpt-4o',- api_key='test_key',- num_retries=2,- retry_min_wait=1,- retry_max_wait=2,- )---def test_handle_nonexistent_issue_reference():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock the requests.get to simulate a 404 error- mock_response = MagicMock()- mock_response.raise_for_status.side_effect = httpx.HTTPError(- '404 Client Error: Not Found'- )-- with patch('httpx.get', return_value=mock_response):- # Call the method with a non-existent issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #999999', # Non-existent issue- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return an empty list since the referenced issue couldn't be fetched- assert result == []---def test_handle_rate_limit_error():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock the requests.get to simulate a rate limit error- mock_response = MagicMock()- mock_response.raise_for_status.side_effect = httpx.HTTPError(- '403 Client Error: Rate Limit Exceeded'- )-- with patch('httpx.get', return_value=mock_response):- # Call the method with an issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #123',- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return an empty list since the request was rate limited- assert result == []---def test_handle_network_error():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock the requests.get to simulate a network error- with patch('httpx.get', side_effect=httpx.NetworkError('Network Error')):- # Call the method with an issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #123',- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return an empty list since the network request failed- assert result == []---def test_successful_issue_reference():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock a successful response- mock_response = MagicMock()- mock_response.raise_for_status.return_value = None- mock_response.json.return_value = {'body': 'This is the referenced issue body'}-- with patch('httpx.get', return_value=mock_response):- # Call the method with an issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #123',- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return a list with the referenced issue body- assert result == ['This is the referenced issue body']---class MockLLMResponse:- """Mock LLM Response class to mimic the actual LLM response structure."""-- class Choice:- class Message:- def __init__(self, content):- self.content = content-- def __init__(self, content):- self.message = self.Message(content)-- def __init__(self, content):- self.choices = [self.Choice(content)]---class DotDict(dict):- """A dictionary that supports dot notation access."""-- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- for key, value in self.items():- if isinstance(value, dict):- self[key] = DotDict(value)- elif isinstance(value, list):- self[key] = [- DotDict(item) if isinstance(item, dict) else item for item in value- ]-- def __getattr__(self, key):- if key in self:- return self[key]- else:- raise AttributeError(- f"'{self.__class__.__name__}' object has no attribute '{key}'"- )-- def __setattr__(self, key, value):- self[key] = value-- def __delattr__(self, key):- if key in self:- del self[key]- else:- raise AttributeError(- f"'{self.__class__.__name__}' object has no attribute '{key}'"- )---@patch('openhands.llm.llm.litellm_completion')-def test_guess_success_rate_limit_wait_time(mock_litellm_completion, default_config):- """Test that the retry mechanism in guess_success respects wait time between retries."""- with patch('time.sleep') as mock_sleep:- # Simulate a rate limit error followed by a successful response- mock_litellm_completion.side_effect = [- RateLimitError(- 'Rate limit exceeded', llm_provider='test_provider', model='test_model'- ),- DotDict(- {- 'choices': [- {- 'message': {- 'content': '--- success\ntrue\n--- explanation\nRetry successful'- }- }- ]- }- ),- ]-- llm = LLM(config=default_config, service_id='test-service')- handler = ServiceContextIssue(- GithubIssueHandler('test-owner', 'test-repo', 'test-token'), default_config- )- handler.llm = llm-- # Mock issue and history- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test Issue',- body='This is a test issue.',- thread_comments=['Please improve error handling'],- )- history = [MessageAction(content='Fixed error handling.')]-- # Call guess_success- success, _, explanation = handler.guess_success(issue, history)-- # Assertions- assert success is True- assert explanation == 'Retry successful'- assert mock_litellm_completion.call_count == 2 # Two attempts made- mock_sleep.assert_called_once() # Sleep called once between retries-- # Validate wait time- wait_time = mock_sleep.call_args[0][0]- assert (- default_config.retry_min_wait <= wait_time <= default_config.retry_max_wait- ), (- f'Expected wait time between {default_config.retry_min_wait} and {default_config.retry_max_wait} seconds, but got {wait_time}'- )---@patch('openhands.llm.llm.litellm_completion')-def test_guess_success_exhausts_retries(mock_completion, default_config):- """Test the retry mechanism in guess_success exhausts retries and raises an error."""- # Simulate persistent rate limit errors by always raising RateLimitError- mock_completion.side_effect = RateLimitError(- 'Rate limit exceeded', llm_provider='test_provider', model='test_model'- )-- # Initialize LLM and handler- llm = LLM(config=default_config, service_id='test-service')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), default_config- )- handler.llm = llm-- # Mock issue and history- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test Issue',- body='This is a test issue.',- thread_comments=['Please improve error handling'],- )- history = [MessageAction(content='Fixed error handling.')]-- # Call guess_success and expect it to raise an error after retries- with pytest.raises(RateLimitError):- handler.guess_success(issue, history)-- # Assertions- assert (- mock_completion.call_count == default_config.num_retries- ) # Initial call + retriesdiff --git a/tests/unit/resolver/github/test_pr_handler_guess_success.py b/tests/unit/resolver/github/test_pr_handler_guess_success.pydeleted file mode 100644index e94b0bdeb9..0000000000--- a/tests/unit/resolver/github/test_pr_handler_guess_success.py+++ /dev/null@@ -1,672 +0,0 @@-import json-from unittest.mock import MagicMock, patch--import pytest--from openhands.core.config import LLMConfig-from openhands.events.action.message import MessageAction-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.github import GithubPRHandler-from openhands.resolver.interfaces.issue import Issue, ReviewThread-from openhands.resolver.interfaces.issue_definitions import ServiceContextPR---def pr_handler():- llm_config = LLMConfig(model='test-model')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )- return handler---def mock_llm_success_response():- return MagicMock(- choices=[- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes look good"""- )- )- ]- )---def test_guess_success_review_threads_litellm_call():- """Test that the completion() call for review threads contains the expected content."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with review threads- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue 1 description', 'Issue 2 description'],- review_comments=None,- review_threads=[- ReviewThread(- comment='Please fix the formatting\n---\nlatest feedback:\nAdd docstrings',- files=['/src/file1.py', '/src/file2.py'],- ),- ReviewThread(- comment='Add more tests\n---\nlatest feedback:\nAdd test cases',- files=['/tests/test_file.py'],- ),- ],- thread_ids=['1', '2'],- head_branch='test-branch',- )-- # Create mock history with a detailed response- history = [- MessageAction(- content="""I have made the following changes:-1. Fixed formatting in file1.py and file2.py-2. Added docstrings to all functions-3. Added test cases in test_file.py"""- )- ]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the completion() calls- assert mock_completion.call_count == 2 # One call per review thread-- # Check first call- first_call = mock_completion.call_args_list[0]- first_prompt = first_call[1]['messages'][0]['content']- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in first_prompt- )- assert (- 'Feedback:\nPlease fix the formatting\n---\nlatest feedback:\nAdd docstrings'- in first_prompt- )- assert (- 'Files locations:\n'- + json.dumps(['/src/file1.py', '/src/file2.py'], indent=4)- in first_prompt- )- assert 'Last message from AI agent:\n' + history[0].content in first_prompt-- # Check second call- second_call = mock_completion.call_args_list[1]- second_prompt = second_call[1]['messages'][0]['content']- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in second_prompt- )- assert (- 'Feedback:\nAdd more tests\n---\nlatest feedback:\nAdd test cases'- in second_prompt- )- assert (- 'Files locations:\n' + json.dumps(['/tests/test_file.py'], indent=4)- in second_prompt- )- assert 'Last message from AI agent:\n' + history[0].content in second_prompt-- assert len(json.loads(explanation)) == 2---def test_guess_success_thread_comments_litellm_call():- """Test that the completion() call for thread comments contains the expected content."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with thread comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=[- 'Please improve error handling',- 'Add input validation',- 'latest feedback:\nHandle edge cases',- ],- closing_issues=['Issue 1 description', 'Issue 2 description'],- review_comments=None,- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history with a detailed response- history = [- MessageAction(- content="""I have made the following changes:-1. Added try/catch blocks for error handling-2. Added input validation checks-3. Added handling for edge cases"""- )- ]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in prompt- )- assert 'PR Thread Comments:\n' + '\n---\n'.join(issue.thread_comments) in prompt- assert 'Last message from AI agent:\n' + history[0].content in prompt-- assert len(json.loads(explanation)) == 1---def test_check_feedback_with_llm():- """Test the _check_feedback_with_llm helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Test cases for different LLM responses- test_cases = [- {- 'response': '--- success\ntrue\n--- explanation\nChanges look good',- 'expected': (True, 'Changes look good'),- },- {- 'response': '--- success\nfalse\n--- explanation\nNot all issues fixed',- 'expected': (False, 'Not all issues fixed'),- },- {- 'response': 'Invalid response format',- 'expected': (- False,- 'Failed to decode answer from LLM response: Invalid response format',- ),- },- {- 'response': '--- success\ntrue\n--- explanation\nMultiline\nexplanation\nhere',- 'expected': (True, 'Multiline\nexplanation\nhere'),- },- ]-- for case in test_cases:- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content=case['response']))]-- # Test the function- with patch.object(LLM, 'completion', return_value=mock_response):- success, explanation = handler._check_feedback_with_llm('test prompt')- assert (success, explanation) == case['expected']---def test_check_review_thread_with_git_patch():- """Test that git patch from complete_runtime is included in the prompt."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_thread = ReviewThread(- comment='Please fix the formatting\n---\nlatest feedback:\nAdd docstrings',- files=['/src/file1.py', '/src/file2.py'],- )- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have fixed the formatting and added docstrings'- git_patch = 'diff --git a/src/file1.py b/src/file1.py\n+"""Added docstring."""\n'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_thread(- review_thread, issues_context, last_message, git_patch- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'Feedback:\n' + review_thread.comment in prompt- assert (- 'Files locations:\n' + json.dumps(review_thread.files, indent=4) in prompt- )- assert 'Last message from AI agent:\n' + last_message in prompt- assert 'Changes made (git patch):\n' + git_patch in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_review_thread():- """Test the _check_review_thread helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_thread = ReviewThread(- comment='Please fix the formatting\n---\nlatest feedback:\nAdd docstrings',- files=['/src/file1.py', '/src/file2.py'],- )- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have fixed the formatting and added docstrings'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_thread(- review_thread, issues_context, last_message- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'Feedback:\n' + review_thread.comment in prompt- assert (- 'Files locations:\n' + json.dumps(review_thread.files, indent=4) in prompt- )- assert 'Last message from AI agent:\n' + last_message in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_thread_comments_with_git_patch():- """Test that git patch from complete_runtime is included in the prompt."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- thread_comments = [- 'Please improve error handling',- 'Add input validation',- 'latest feedback:\nHandle edge cases',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have added error handling and input validation'- git_patch = 'diff --git a/src/file1.py b/src/file1.py\n+try:\n+ validate_input()\n+except ValueError:\n+ handle_error()\n'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_thread_comments(- thread_comments, issues_context, last_message, git_patch- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Thread Comments:\n' + '\n---\n'.join(thread_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt- assert 'Changes made (git patch):\n' + git_patch in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_thread_comments():- """Test the _check_thread_comments helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- thread_comments = [- 'Please improve error handling',- 'Add input validation',- 'latest feedback:\nHandle edge cases',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have added error handling and input validation'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_thread_comments(- thread_comments, issues_context, last_message- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Thread Comments:\n' + '\n---\n'.join(thread_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_review_comments_with_git_patch():- """Test that git patch from complete_runtime is included in the prompt."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_comments = [- 'Please fix the code style',- 'Add more test cases',- 'latest feedback:\nImprove documentation',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have fixed the code style and added tests'- git_patch = 'diff --git a/src/file1.py b/src/file1.py\n+"""This module does X."""\n+def func():\n+ """Do Y."""\n'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_comments(- review_comments, issues_context, last_message, git_patch- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Review Comments:\n' + '\n---\n'.join(review_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt- assert 'Changes made (git patch):\n' + git_patch in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_review_comments():- """Test the _check_review_comments helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_comments = [- 'Please improve code readability',- 'Add comments to complex functions',- 'Follow PEP 8 style guide',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have improved code readability and added comments'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_comments(- review_comments, issues_context, last_message- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Review Comments:\n' + '\n---\n'.join(review_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_guess_success_review_comments_litellm_call():- """Test that the completion() call for review comments contains the expected content."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GithubPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with review comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue 1 description', 'Issue 2 description'],- review_comments=[- 'Please improve code readability',- 'Add comments to complex functions',- 'Follow PEP 8 style guide',- ],- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history with a detailed response- history = [- MessageAction(- content="""I have made the following changes:-1. Improved code readability by breaking down complex functions-2. Added detailed comments to all complex functions-3. Fixed code style to follow PEP 8"""- )- ]-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in prompt- )- assert 'PR Review Comments:\n' + '\n---\n'.join(issue.review_comments) in prompt- assert 'Last message from AI agent:\n' + history[0].content in prompt-- assert len(json.loads(explanation)) == 1diff --git a/tests/unit/resolver/github/test_pr_title_escaping.py b/tests/unit/resolver/github/test_pr_title_escaping.pydeleted file mode 100644index 5832473860..0000000000--- a/tests/unit/resolver/github/test_pr_title_escaping.py+++ /dev/null@@ -1,166 +0,0 @@-import os-import subprocess-import tempfile--from openhands.integrations.service_types import ProviderType-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.send_pull_request import make_commit---def test_commit_message_with_quotes():- # Create a temporary directory and initialize git repo- with tempfile.TemporaryDirectory() as temp_dir:- subprocess.run(['git', 'init', temp_dir], check=True)-- # Create a test file and add it to git- test_file = os.path.join(temp_dir, 'test.txt')- with open(test_file, 'w') as f:- f.write('test content')-- subprocess.run(['git', '-C', temp_dir, 'add', 'test.txt'], check=True)-- # Create a test issue with problematic title- issue = Issue(- owner='test-owner',- repo='test-repo',- number=123,- title="Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>",- body='Test body',- labels=[],- assignees=[],- state='open',- created_at='2024-01-01T00:00:00Z',- updated_at='2024-01-01T00:00:00Z',- closed_at=None,- head_branch=None,- thread_ids=None,- )-- # Make the commit- make_commit(temp_dir, issue, 'issue')-- # Get the commit message- result = subprocess.run(- ['git', '-C', temp_dir, 'log', '-1', '--pretty=%B'],- capture_output=True,- text=True,- check=True,- )- commit_msg = result.stdout.strip()-- # The commit message should contain the quotes without excessive escaping- expected = "Fix issue #123: Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>"- assert commit_msg == expected, f'Expected: {expected}\nGot: {commit_msg}'---def test_pr_title_with_quotes(monkeypatch):- # Mock requests.post to avoid actual API calls- class MockResponse:- def __init__(self, status_code=201):- self.status_code = status_code- self.text = ''-- def json(self):- return {'html_url': 'https://github.com/test/test/pull/1'}-- def raise_for_status(self):- pass-- def mock_post(*args, **kwargs):- # Verify that the PR title is not over-escaped- data = kwargs.get('json', {})- title = data.get('title', '')- expected = "Fix issue #123: Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>"- assert title == expected, (- f'PR title was incorrectly escaped.\nExpected: {expected}\nGot: {title}'- )- return MockResponse()-- class MockGetResponse:- def __init__(self, status_code=200):- self.status_code = status_code- self.text = ''-- def json(self):- return {'default_branch': 'main'}-- def raise_for_status(self):- pass-- monkeypatch.setattr('httpx.post', mock_post)- monkeypatch.setattr('httpx.get', lambda *args, **kwargs: MockGetResponse())- monkeypatch.setattr(- 'openhands.resolver.interfaces.github.GithubIssueHandler.branch_exists',- lambda *args, **kwargs: False,- )-- # Mock subprocess.run to avoid actual git commands- original_run = subprocess.run-- def mock_run(*args, **kwargs):- print(f'Running command: {args[0] if args else kwargs.get("args", [])}')- if isinstance(args[0], list) and args[0][0] == 'git':- if 'push' in args[0]:- return subprocess.CompletedProcess(- args[0], returncode=0, stdout='', stderr=''- )- return original_run(*args, **kwargs)- return original_run(*args, **kwargs)-- monkeypatch.setattr('subprocess.run', mock_run)-- # Create a temporary directory and initialize git repo- with tempfile.TemporaryDirectory() as temp_dir:- print('Initializing git repo...')- subprocess.run(['git', 'init', temp_dir], check=True)-- # Add these lines to configure git- subprocess.run(- ['git', '-C', temp_dir, 'config', 'user.name', 'Test User'], check=True- )- subprocess.run(- ['git', '-C', temp_dir, 'config', 'user.email', '[email protected]'],- check=True,- )-- # Create a test file and add it to git- test_file = os.path.join(temp_dir, 'test.txt')- with open(test_file, 'w') as f:- f.write('test content')-- print('Adding and committing test file...')- subprocess.run(['git', '-C', temp_dir, 'add', 'test.txt'], check=True)- subprocess.run(- ['git', '-C', temp_dir, 'commit', '-m', 'Initial commit'], check=True- )-- # Create a test issue with problematic title- print('Creating test issue...')- issue = Issue(- owner='test-owner',- repo='test-repo',- number=123,- title="Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>",- body='Test body',- labels=[],- assignees=[],- state='open',- created_at='2024-01-01T00:00:00Z',- updated_at='2024-01-01T00:00:00Z',- closed_at=None,- head_branch=None,- thread_ids=None,- )-- # Try to send a PR - this will fail if the title is incorrectly escaped- print('Sending PR...')- from openhands.resolver.send_pull_request import send_pull_request-- send_pull_request(- issue=issue,- token='dummy-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=temp_dir,- pr_type='ready',- )diff --git a/tests/unit/resolver/github/test_resolve_issues.py b/tests/unit/resolver/github/test_resolve_issues.pydeleted file mode 100644index 002735e9b7..0000000000--- a/tests/unit/resolver/github/test_resolve_issues.py+++ /dev/null@@ -1,1046 +0,0 @@-import os-import tempfile-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openhands.core.config import LLMConfig-from openhands.events.action import CmdRunAction, MessageAction-from openhands.events.observation import (- CmdOutputMetadata,- CmdOutputObservation,- NullObservation,-)-from openhands.integrations.service_types import ProviderType-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandler-from openhands.resolver.interfaces.issue import Issue, ReviewThread-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)-from openhands.resolver.issue_resolver import IssueResolver-from openhands.resolver.resolver_output import ResolverOutput---def default_mock_args():- """Fixture that provides a default mock args object with common values.-- Tests can override specific attributes as needed.- """- mock_args = MagicMock()- mock_args.selected_repo = 'test-owner/test-repo'- mock_args.token = 'test-token'- mock_args.username = 'test-user'- mock_args.max_iterations = 5- mock_args.output_dir = '/tmp'- mock_args.llm_model = 'test'- mock_args.llm_api_key = 'test'- mock_args.llm_base_url = None- mock_args.base_domain = None- mock_args.runtime_container_image = None- mock_args.base_container_image = None- mock_args.is_experimental = False- mock_args.issue_number = None- mock_args.comment_id = None- mock_args.repo_instruction_file = None- mock_args.issue_type = 'issue'- mock_args.prompt_file = None- return mock_args---def mock_github_token():- """Fixture that patches the identify_token function to return GitHub provider type.-- This eliminates the need for repeated patching in each test function.- """- with patch(- 'openhands.resolver.issue_resolver.identify_token',- return_value=ProviderType.GITHUB,- ) as patched:- yield patched---def mock_output_dir():- with tempfile.TemporaryDirectory() as temp_dir:- repo_path = os.path.join(temp_dir, 'repo')- # Initialize a GitHub repo in "repo" and add a commit with "README.md"- os.makedirs(repo_path)- os.system(f'git init {repo_path}')- readme_path = os.path.join(repo_path, 'README.md')- with open(readme_path, 'w') as f:- f.write('hello world')- os.system(f'git -C {repo_path} add README.md')- os.system(f"git -C {repo_path} commit -m 'Initial commit'")- yield temp_dir---def mock_subprocess():- with patch('subprocess.check_output') as mock_check_output:- yield mock_check_output---def mock_os():- with patch('os.system') as mock_system, patch('os.path.join') as mock_join:- yield mock_system, mock_join---def mock_user_instructions_template():- return 'Issue: {{ body }}\n\nPlease fix this issue.'---def mock_conversation_instructions_template():- return 'Instructions: {{ repo_instruction }}'---def mock_followup_prompt_template():- return 'Issue context: {{ issues }}\n\nReview comments: {{ review_comments }}\n\nReview threads: {{ review_threads }}\n\nFiles: {{ files }}\n\nThread comments: {{ thread_context }}\n\nPlease fix this issue.'---def create_cmd_output(exit_code: int, content: str, command: str):- return CmdOutputObservation(- content=content,- command=command,- metadata=CmdOutputMetadata(exit_code=exit_code),- )---def test_initialize_runtime(default_mock_args, mock_github_token):- mock_runtime = MagicMock()- mock_runtime.run_action.side_effect = [- create_cmd_output(exit_code=0, content='', command='cd /workspace'),- create_cmd_output(- exit_code=0, content='', command='git config --global core.pager ""'- ),- ]-- # Create resolver with mocked token identification- resolver = IssueResolver(default_mock_args)-- resolver.initialize_runtime(mock_runtime)-- assert mock_runtime.run_action.call_count == 2- mock_runtime.run_action.assert_any_call(CmdRunAction(command='cd /workspace'))- mock_runtime.run_action.assert_any_call(- CmdRunAction(command='git config --global core.pager ""')- )---async def test_resolve_issue_no_issues_found(default_mock_args, mock_github_token):- """Test the resolve_issue method when no issues are found."""- # Mock dependencies- mock_handler = MagicMock()- mock_handler.get_converted_issues.return_value = [] # Return empty list-- # Customize the mock args for this test- default_mock_args.issue_number = 5432-- # Create a resolver instance with mocked token identification- resolver = IssueResolver(default_mock_args)-- # Mock the issue handler- resolver.issue_handler = mock_handler-- # Test that the correct exception is raised- with pytest.raises(ValueError) as exc_info:- await resolver.resolve_issue()-- # Verify the error message- assert 'No issues found for issue number 5432' in str(exc_info.value)- assert 'test-owner/test-repo' in str(exc_info.value)-- mock_handler.get_converted_issues.assert_called_once_with(- issue_numbers=[5432], comment_id=None- )---def test_download_issues_from_github():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), llm_config- )-- mock_issues_response = MagicMock()- mock_issues_response.json.side_effect = [- [- {'number': 1, 'title': 'Issue 1', 'body': 'This is an issue'},- {- 'number': 2,- 'title': 'PR 1',- 'body': 'This is a pull request',- 'pull_request': {},- },- {'number': 3, 'title': 'Issue 2', 'body': 'This is another issue'},- ],- None,- ]- mock_issues_response.raise_for_status = MagicMock()-- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = []- mock_comments_response.raise_for_status = MagicMock()-- def get_mock_response(url, *args, **kwargs):- if '/comments' in url:- return mock_comments_response- return mock_issues_response-- with patch('httpx.get', side_effect=get_mock_response):- issues = handler.get_converted_issues(issue_numbers=[1, 3])-- assert len(issues) == 2- assert handler.issue_type == 'issue'- assert all(isinstance(issue, Issue) for issue in issues)- assert [issue.number for issue in issues] == [1, 3]- assert [issue.title for issue in issues] == ['Issue 1', 'Issue 2']- assert [issue.review_comments for issue in issues] == [None, None]- assert [issue.closing_issues for issue in issues] == [None, None]- assert [issue.thread_ids for issue in issues] == [None, None]---def test_download_pr_from_github():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(GithubPRHandler('owner', 'repo', 'token'), llm_config)- mock_pr_response = MagicMock()- mock_pr_response.json.side_effect = [- [- {- 'number': 1,- 'title': 'PR 1',- 'body': 'This is a pull request',- 'head': {'ref': 'b1'},- },- {- 'number': 2,- 'title': 'My PR',- 'body': 'This is another pull request',- 'head': {'ref': 'b2'},- },- {'number': 3, 'title': 'PR 3', 'body': 'Final PR', 'head': {'ref': 'b3'}},- ],- None,- ]- mock_pr_response.raise_for_status = MagicMock()-- # Mock for PR comments response- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [] # No PR comments- mock_comments_response.raise_for_status = MagicMock()-- # Mock for GraphQL request (for download_pr_metadata)- mock_graphql_response = MagicMock()- mock_graphql_response.json.side_effect = lambda: {- 'data': {- 'repository': {- 'pullRequest': {- 'closingIssuesReferences': {- 'edges': [- {'node': {'body': 'Issue 1 body', 'number': 1}},- {'node': {'body': 'Issue 2 body', 'number': 2}},- ]- },- 'reviewThreads': {- 'edges': [- {- 'node': {- 'isResolved': False,- 'id': '1',- 'comments': {- 'nodes': [- {- 'body': 'Unresolved comment 1',- 'path': '/frontend/header.tsx',- },- {'body': 'Follow up thread'},- ]- },- }- },- {- 'node': {- 'isResolved': True,- 'id': '2',- 'comments': {- 'nodes': [- {- 'body': 'Resolved comment 1',- 'path': '/some/file.py',- }- ]- },- }- },- {- 'node': {- 'isResolved': False,- 'id': '3',- 'comments': {- 'nodes': [- {- 'body': 'Unresolved comment 3',- 'path': '/another/file.py',- }- ]- },- }- },- ]- },- }- }- }- }-- mock_graphql_response.raise_for_status = MagicMock()-- def get_mock_response(url, *args, **kwargs):- if '/comments' in url:- return mock_comments_response- return mock_pr_response-- with patch('httpx.get', side_effect=get_mock_response):- with patch('httpx.post', return_value=mock_graphql_response):- issues = handler.get_converted_issues(issue_numbers=[1, 2, 3])-- assert len(issues) == 3- assert handler.issue_type == 'pr'- assert all(isinstance(issue, Issue) for issue in issues)- assert [issue.number for issue in issues] == [1, 2, 3]- assert [issue.title for issue in issues] == ['PR 1', 'My PR', 'PR 3']- assert [issue.head_branch for issue in issues] == ['b1', 'b2', 'b3']-- assert len(issues[0].review_threads) == 2 # Only unresolved threads- assert (- issues[0].review_threads[0].comment- == 'Unresolved comment 1\n---\nlatest feedback:\nFollow up thread\n'- )- assert issues[0].review_threads[0].files == ['/frontend/header.tsx']- assert (- issues[0].review_threads[1].comment- == 'latest feedback:\nUnresolved comment 3\n'- )- assert issues[0].review_threads[1].files == ['/another/file.py']- assert issues[0].closing_issues == ['Issue 1 body', 'Issue 2 body']- assert issues[0].thread_ids == ['1', '3']---async def test_complete_runtime(default_mock_args, mock_github_token):- """Test the complete_runtime method."""- mock_runtime = MagicMock()- mock_runtime.run_action.side_effect = [- create_cmd_output(exit_code=0, content='', command='cd /workspace'),- create_cmd_output(- exit_code=0, content='', command='git config --global core.pager ""'- ),- create_cmd_output(- exit_code=0,- content='',- command='git config --global --add safe.directory /workspace',- ),- create_cmd_output(- exit_code=0, content='', command='git diff base_commit_hash fix'- ),- create_cmd_output(exit_code=0, content='git diff content', command='git apply'),- ]-- # Create resolver with mocked token identification- resolver = IssueResolver(default_mock_args)-- result = await resolver.complete_runtime(mock_runtime, 'base_commit_hash')-- assert result == {'git_patch': 'git diff content'}- assert mock_runtime.run_action.call_count == 5--- 'test_case',- [- {- 'name': 'successful_run',- 'run_controller_return': MagicMock(- history=[NullObservation(content='')],- metrics=MagicMock(- get=MagicMock(return_value={'test_result': 'passed'})- ),- last_error=None,- ),- 'run_controller_raises': None,- 'expected_success': True,- 'expected_error': None,- 'expected_explanation': 'Issue resolved successfully',- 'is_pr': False,- 'comment_success': None,- },- {- 'name': 'value_error',- 'run_controller_return': None,- 'run_controller_raises': ValueError('Test value error'),- 'expected_success': False,- 'expected_error': 'Agent failed to run or crashed',- 'expected_explanation': 'Agent failed to run',- 'is_pr': False,- 'comment_success': None,- },- {- 'name': 'runtime_error',- 'run_controller_return': None,- 'run_controller_raises': RuntimeError('Test runtime error'),- 'expected_success': False,- 'expected_error': 'Agent failed to run or crashed',- 'expected_explanation': 'Agent failed to run',- 'is_pr': False,- 'comment_success': None,- },- {- 'name': 'json_decode_error',- 'run_controller_return': MagicMock(- history=[NullObservation(content='')],- metrics=MagicMock(- get=MagicMock(return_value={'test_result': 'passed'})- ),- last_error=None,- ),- 'run_controller_raises': None,- 'expected_success': True,- 'expected_error': None,- 'expected_explanation': 'Non-JSON explanation',- 'is_pr': True,- 'comment_success': [- True,- False,- ], # To trigger the PR success logging code path- },- ],-)-async def test_process_issue(- default_mock_args,- mock_github_token,- mock_output_dir,- mock_user_instructions_template,- test_case,-):- """Test the process_issue method with different scenarios."""- # Set up test data- issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- base_commit = 'abcdef1234567890'-- # Customize the mock args for this test- default_mock_args.output_dir = mock_output_dir- default_mock_args.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'-- # Create a resolver instance with mocked token identification- resolver = IssueResolver(default_mock_args)- resolver.user_instructions_prompt_template = mock_user_instructions_template-- # Mock the handler with LLM config- llm_config = LLMConfig(model='test', api_key='test')- handler_instance = MagicMock()- handler_instance.guess_success.return_value = (- test_case['expected_success'],- test_case.get('comment_success', None),- test_case['expected_explanation'],- )- handler_instance.get_instruction.return_value = (- 'Test instruction',- 'Test conversation instructions',- [],- )- handler_instance.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'- handler_instance.llm = LLM(llm_config, service_id='test-service')-- # Mock the runtime and its methods- mock_runtime = MagicMock()- mock_runtime.connect = AsyncMock()- mock_runtime.run_action.return_value = CmdOutputObservation(- content='test patch',- command='git diff',- metadata=CmdOutputMetadata(exit_code=0),- )- mock_runtime.event_stream.subscribe = MagicMock()-- # Mock the create_runtime function- mock_create_runtime = MagicMock(return_value=mock_runtime)-- # Mock the run_controller function- mock_run_controller = AsyncMock()- if test_case['run_controller_raises']:- mock_run_controller.side_effect = test_case['run_controller_raises']- else:- mock_run_controller.return_value = test_case['run_controller_return']-- # Patch the necessary functions and methods- with (- patch('openhands.resolver.issue_resolver.create_runtime', mock_create_runtime),- patch('openhands.resolver.issue_resolver.run_controller', mock_run_controller),- patch.object(- resolver, 'complete_runtime', return_value={'git_patch': 'test patch'}- ),- patch.object(resolver, 'initialize_runtime') as mock_initialize_runtime,- ):- # Call the process_issue method- result = await resolver.process_issue(issue, base_commit, handler_instance)-- # Assert the result matches our expectations- assert isinstance(result, ResolverOutput)- assert result.issue == issue- assert result.base_commit == base_commit- assert result.git_patch == 'test patch'- assert result.success == test_case['expected_success']- assert result.result_explanation == test_case['expected_explanation']- assert result.error == test_case['expected_error']-- # Assert that the mocked functions were called- mock_create_runtime.assert_called_once()- mock_runtime.connect.assert_called_once()- mock_initialize_runtime.assert_called_once()- mock_run_controller.assert_called_once()- resolver.complete_runtime.assert_awaited_once_with(mock_runtime, base_commit)-- # Assert run_controller was called with the right parameters- if not test_case['run_controller_raises']:- # Check that the first positional argument is a config- assert 'config' in mock_run_controller.call_args[1]- # Check that initial_user_action is a MessageAction with the right content- assert isinstance(- mock_run_controller.call_args[1]['initial_user_action'], MessageAction- )- assert mock_run_controller.call_args[1]['runtime'] == mock_runtime-- # Assert that guess_success was called only for successful runs- if test_case['expected_success']:- handler_instance.guess_success.assert_called_once()- else:- handler_instance.guess_success.assert_not_called()---def test_get_instruction(- mock_user_instructions_template,- mock_conversation_instructions_template,- mock_followup_prompt_template,-):- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue refer to image ',- )- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, images_urls = issue_handler.get_instruction(- issue,- mock_user_instructions_template,- mock_conversation_instructions_template,- None,- )- expected_instruction = 'Issue: Test Issue\n\nThis is a test issue refer to image \n\nPlease fix this issue.'-- assert images_urls == ['https://sampleimage.com/image1.png']- assert issue_handler.issue_type == 'issue'- assert instruction == expected_instruction- assert conversation_instructions is not None-- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue',- closing_issues=['Issue 1 fix the type'],- review_threads=[- ReviewThread(- comment="There is still a typo 'pthon' instead of 'python'", files=[]- )- ],- thread_comments=[- "I've left review comments, please address them",- 'This is a valid concern.',- ],- )-- pr_handler = ServiceContextPR(- GithubPRHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, images_urls = pr_handler.get_instruction(- issue,- mock_followup_prompt_template,- mock_conversation_instructions_template,- None,- )- expected_instruction = "Issue context: [\n \"Issue 1 fix the type\"\n]\n\nReview comments: None\n\nReview threads: [\n \"There is still a typo 'pthon' instead of 'python'\"\n]\n\nFiles: []\n\nThread comments: I've left review comments, please address them\n---\nThis is a valid concern.\n\nPlease fix this issue."-- assert images_urls == []- assert pr_handler.issue_type == 'pr'- # Compare content ignoring exact formatting- assert "There is still a typo 'pthon' instead of 'python'" in instruction- assert "I've left review comments, please address them" in instruction- assert 'This is a valid concern' in instruction- assert conversation_instructions is not None---def test_file_instruction():- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue ',- )- # load prompt from openhands/resolver/prompts/resolve/basic.jinja- with open('openhands/resolver/prompts/resolve/basic.jinja', 'r') as f:- prompt = f.read()-- with open(- 'openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja', 'r'- ) as f:- conversation_instructions_template = f.read()-- # Test without thread comments- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, images_urls = issue_handler.get_instruction(- issue, prompt, conversation_instructions_template, None- )- expected_instruction = """Please fix the following issue for the repository in /workspace.-An environment has been set up for you to start working. You may assume all necessary tools are installed.--# Problem Statement-Test Issue--This is a test issue """-- expected_conversation_instructions = """IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.-You SHOULD INCLUDE PROPER INDENTATION in your edit commands.--When you think you have fixed the issue through code changes, please finish the interaction."""-- assert instruction == expected_instruction- assert conversation_instructions == expected_conversation_instructions-- assert images_urls == ['https://sampleimage.com/sample.png']---def test_file_instruction_with_repo_instruction():- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue',- )- # load prompt from openhands/resolver/prompts/resolve/basic.jinja- with open('openhands/resolver/prompts/resolve/basic.jinja', 'r') as f:- prompt = f.read()-- with open(- 'openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja', 'r'- ) as f:- conversation_instructions_prompt = f.read()-- # load repo instruction from openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands-resolver.txt- with open(- 'openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands-resolver.txt',- 'r',- ) as f:- repo_instruction = f.read()-- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, image_urls = issue_handler.get_instruction(- issue, prompt, conversation_instructions_prompt, repo_instruction- )-- expected_instruction = """Please fix the following issue for the repository in /workspace.-An environment has been set up for you to start working. You may assume all necessary tools are installed.--# Problem Statement-Test Issue--This is a test issue"""-- expected_conversation_instructions = """IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.-You SHOULD INCLUDE PROPER INDENTATION in your edit commands.--Some basic information about this repository:-This is a Python repo for openhands-resolver, a library that attempts to resolve github issues with the AI agent OpenHands.--- Setup: `poetry install --with test --with dev`-- Testing: `poetry run pytest tests/test_*.py`---When you think you have fixed the issue through code changes, please finish the interaction."""-- assert instruction == expected_instruction- assert conversation_instructions == expected_conversation_instructions- assert conversation_instructions is not None- assert issue_handler.issue_type == 'issue'- assert image_urls == []---def test_guess_success():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- mock_history = [create_cmd_output(exit_code=0, content='', command='cd /workspace')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\ntrue\n--- explanation\nIssue resolved successfully'- )- )- ]- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert success- assert explanation == 'Issue resolved successfully'---def test_guess_success_with_thread_comments():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- thread_comments=[- 'First comment',- 'Second comment',- 'latest feedback:\nPlease add tests',- ],- )- mock_history = [MagicMock(message='I have added tests for this case')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\ntrue\n--- explanation\nTests have been added to verify thread comments handling'- )- )- ]- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert success- assert 'Tests have been added' in explanation---def test_instruction_with_thread_comments():- # Create an issue with thread comments- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue',- thread_comments=[- 'First comment',- 'Second comment',- 'latest feedback:\nPlease add tests',- ],- )-- # Load the basic prompt template- with open('openhands/resolver/prompts/resolve/basic.jinja', 'r') as f:- prompt = f.read()-- with open(- 'openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja', 'r'- ) as f:- conversation_instructions_template = f.read()-- llm_config = LLMConfig(model='test', api_key='test')- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), llm_config- )- instruction, _, images_urls = issue_handler.get_instruction(- issue, prompt, conversation_instructions_template, None- )-- # Verify that thread comments are included in the instruction- assert 'First comment' in instruction- assert 'Second comment' in instruction- assert 'Please add tests' in instruction- assert 'Issue Thread Comments:' in instruction- assert images_urls == []---def test_guess_success_failure():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- thread_comments=[- 'First comment',- 'Second comment',- 'latest feedback:\nPlease add tests',- ],- )- mock_history = [MagicMock(message='I have added tests for this case')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\ntrue\n--- explanation\nTests have been added to verify thread comments handling'- )- )- ]- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert success- assert 'Tests have been added' in explanation---def test_guess_success_negative_case():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- mock_history = [create_cmd_output(exit_code=0, content='', command='cd /workspace')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\nfalse\n--- explanation\nIssue not resolved'- )- )- ]- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert not success- assert explanation == 'Issue not resolved'---def test_guess_success_invalid_output():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- mock_history = [create_cmd_output(exit_code=0, content='', command='cd /workspace')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(message=MagicMock(content='This is not a valid output'))- ]- issue_handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert not success- assert (- explanation- == 'Failed to decode answer from LLM response: This is not a valid output'- )---def test_download_pr_with_review_comments():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(GithubPRHandler('owner', 'repo', 'token'), llm_config)- mock_pr_response = MagicMock()- mock_pr_response.json.side_effect = [- [- {- 'number': 1,- 'title': 'PR 1',- 'body': 'This is a pull request',- 'head': {'ref': 'b1'},- },- ],- None,- ]- mock_pr_response.raise_for_status = MagicMock()-- # Mock for PR comments response- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [] # No PR comments- mock_comments_response.raise_for_status = MagicMock()-- # Mock for GraphQL request with review comments but no threads- mock_graphql_response = MagicMock()- mock_graphql_response.json.side_effect = lambda: {- 'data': {- 'repository': {- 'pullRequest': {- 'closingIssuesReferences': {'edges': []},- 'reviews': {- 'nodes': [- {'body': 'Please fix this typo'},- {'body': 'Add more tests'},- ]- },- }- }- }- }-- mock_graphql_response.raise_for_status = MagicMock()-- def get_mock_response(url, *args, **kwargs):- if '/comments' in url:- return mock_comments_response- return mock_pr_response-- with patch('httpx.get', side_effect=get_mock_response):- with patch('httpx.post', return_value=mock_graphql_response):- issues = handler.get_converted_issues(issue_numbers=[1])-- assert len(issues) == 1- assert handler.issue_type == 'pr'- assert isinstance(issues[0], Issue)- assert issues[0].number == 1- assert issues[0].title == 'PR 1'- assert issues[0].head_branch == 'b1'-- # Verify review comments are set but threads are empty- assert len(issues[0].review_comments) == 2- assert issues[0].review_comments[0] == 'Please fix this typo'- assert issues[0].review_comments[1] == 'Add more tests'- assert not issues[0].review_threads- assert not issues[0].closing_issues- assert not issues[0].thread_ids---def test_download_issue_with_specific_comment():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GithubIssueHandler('owner', 'repo', 'token'), llm_config- )-- # Define the specific comment_id to filter- specific_comment_id = 101-- # Mock issue and comment responses- mock_issue_response = MagicMock()- mock_issue_response.json.side_effect = [- [- {'number': 1, 'title': 'Issue 1', 'body': 'This is an issue'},- ],- None,- ]- mock_issue_response.raise_for_status = MagicMock()-- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {- 'id': specific_comment_id,- 'body': 'Specific comment body',- 'issue_url': 'https://api.github.com/repos/owner/repo/issues/1',- },- {- 'id': 102,- 'body': 'Another comment body',- 'issue_url': 'https://api.github.com/repos/owner/repo/issues/2',- },- ]- mock_comments_response.raise_for_status = MagicMock()-- def get_mock_response(url, *args, **kwargs):- if '/comments' in url:- return mock_comments_response-- return mock_issue_response-- with patch('httpx.get', side_effect=get_mock_response):- issues = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- assert len(issues) == 1- assert issues[0].number == 1- assert issues[0].title == 'Issue 1'- assert issues[0].thread_comments == ['Specific comment body']---if __name__ == '__main__':- pytest.main()diff --git a/tests/unit/resolver/github/test_send_pull_request.py b/tests/unit/resolver/github/test_send_pull_request.pydeleted file mode 100644index 3008d3c57f..0000000000--- a/tests/unit/resolver/github/test_send_pull_request.py+++ /dev/null@@ -1,1449 +0,0 @@-import os-import tempfile-from unittest.mock import ANY, MagicMock, call, patch--import pytest--from openhands.core.config import LLMConfig-from openhands.integrations.service_types import ProviderType-from openhands.resolver.interfaces.github import GithubIssueHandler-from openhands.resolver.interfaces.issue import ReviewThread-from openhands.resolver.resolver_output import Issue, ResolverOutput-from openhands.resolver.send_pull_request import (- apply_patch,- initialize_repo,- load_single_resolver_output,- main,- make_commit,- process_single_issue,- send_pull_request,- update_existing_pull_request,-)---def mock_output_dir():- with tempfile.TemporaryDirectory() as temp_dir:- repo_path = os.path.join(temp_dir, 'repo')- # Initialize a GitHub repo in "repo" and add a commit with "README.md"- os.makedirs(repo_path)- os.system(f'git init {repo_path}')- readme_path = os.path.join(repo_path, 'README.md')- with open(readme_path, 'w') as f:- f.write('hello world')- os.system(f'git -C {repo_path} add README.md')- os.system(f"git -C {repo_path} commit -m 'Initial commit'")- yield temp_dir---def mock_issue():- return Issue(- number=42,- title='Test Issue',- owner='test-owner',- repo='test-repo',- body='Test body',- )---def mock_llm_config():- return LLMConfig()---def test_load_single_resolver_output():- mock_output_jsonl = 'tests/unit/resolver/mock_output/output.jsonl'-- # Test loading an existing issue- resolver_output = load_single_resolver_output(mock_output_jsonl, 5)- assert isinstance(resolver_output, ResolverOutput)- assert resolver_output.issue.number == 5- assert resolver_output.issue.title == 'Add MIT license'- assert resolver_output.issue.owner == 'neubig'- assert resolver_output.issue.repo == 'pr-viewer'-- # Test loading a non-existent issue- with pytest.raises(ValueError):- load_single_resolver_output(mock_output_jsonl, 999)---def test_apply_patch(mock_output_dir):- # Create a sample file in the mock repo- sample_file = os.path.join(mock_output_dir, 'sample.txt')- with open(sample_file, 'w') as f:- f.write('Original content')-- # Create a sample patch- patch_content = """-diff --git a/sample.txt b/sample.txt-index 9daeafb..b02def2 100644---- a/sample.txt-+++ b/sample.txt-@@ -1 +1,2 @@--Original content-+Updated content-+New line-"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the file was updated correctly- with open(sample_file, 'r') as f:- updated_content = f.read()-- assert updated_content.strip() == 'Updated content\nNew line'.strip()---def test_apply_patch_preserves_line_endings(mock_output_dir):- # Create sample files with different line endings- unix_file = os.path.join(mock_output_dir, 'unix_style.txt')- dos_file = os.path.join(mock_output_dir, 'dos_style.txt')-- with open(unix_file, 'w', newline='\n') as f:- f.write('Line 1\nLine 2\nLine 3')-- with open(dos_file, 'w', newline='\r\n') as f:- f.write('Line 1\r\nLine 2\r\nLine 3')-- # Create patches for both files- unix_patch = """-diff --git a/unix_style.txt b/unix_style.txt-index 9daeafb..b02def2 100644---- a/unix_style.txt-+++ b/unix_style.txt-@@ -1,3 +1,3 @@- Line 1--Line 2-+Updated Line 2- Line 3-"""-- dos_patch = """-diff --git a/dos_style.txt b/dos_style.txt-index 9daeafb..b02def2 100644---- a/dos_style.txt-+++ b/dos_style.txt-@@ -1,3 +1,3 @@- Line 1--Line 2-+Updated Line 2- Line 3-"""-- # Apply patches- apply_patch(mock_output_dir, unix_patch)- apply_patch(mock_output_dir, dos_patch)-- # Check if line endings are preserved- with open(unix_file, 'rb') as f:- unix_content = f.read()- with open(dos_file, 'rb') as f:- dos_content = f.read()-- assert b'\r\n' not in unix_content, (- 'Unix-style line endings were changed to DOS-style'- )- assert b'\r\n' in dos_content, 'DOS-style line endings were changed to Unix-style'-- # Check if content was updated correctly- assert unix_content.decode('utf-8').split('\n')[1] == 'Updated Line 2'- assert dos_content.decode('utf-8').split('\r\n')[1] == 'Updated Line 2'---def test_apply_patch_create_new_file(mock_output_dir):- # Create a patch that adds a new file- patch_content = """-diff --git a/new_file.txt b/new_file.txt-new file mode 100644-index 0000000..3b18e51---- /dev/null-+++ b/new_file.txt-@@ -0,0 +1 @@-+hello world-"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the new file was created- new_file_path = os.path.join(mock_output_dir, 'new_file.txt')- assert os.path.exists(new_file_path), 'New file was not created'-- # Check if the file content is correct- with open(new_file_path, 'r') as f:- content = f.read().strip()- assert content == 'hello world', 'File content is incorrect'---def test_apply_patch_rename_file(mock_output_dir):- # Create a sample file in the mock repo- old_file = os.path.join(mock_output_dir, 'old_name.txt')- with open(old_file, 'w') as f:- f.write('This file will be renamed')-- # Create a patch that renames the file- patch_content = """diff --git a/old_name.txt b/new_name.txt-similarity index 100%-rename from old_name.txt-rename to new_name.txt"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the file was renamed- new_file = os.path.join(mock_output_dir, 'new_name.txt')- assert not os.path.exists(old_file), 'Old file still exists'- assert os.path.exists(new_file), 'New file was not created'-- # Check if the content is preserved- with open(new_file, 'r') as f:- content = f.read()- assert content == 'This file will be renamed'---def test_apply_patch_delete_file(mock_output_dir):- # Create a sample file in the mock repo- sample_file = os.path.join(mock_output_dir, 'to_be_deleted.txt')- with open(sample_file, 'w') as f:- f.write('This file will be deleted')-- # Create a patch that deletes the file- patch_content = """-diff --git a/to_be_deleted.txt b/to_be_deleted.txt-deleted file mode 100644-index 9daeafb..0000000---- a/to_be_deleted.txt-+++ /dev/null-@@ -1 +0,0 @@--This file will be deleted-"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the file was deleted- assert not os.path.exists(sample_file), 'File was not deleted'---def test_initialize_repo(mock_output_dir):- issue_type = 'issue'- # Copy the repo to patches- ISSUE_NUMBER = 3- initialize_repo(mock_output_dir, ISSUE_NUMBER, issue_type)- patches_dir = os.path.join(mock_output_dir, 'patches', f'issue_{ISSUE_NUMBER}')-- # Check if files were copied correctly- assert os.path.exists(os.path.join(patches_dir, 'README.md'))-- # Check file contents- with open(os.path.join(patches_dir, 'README.md'), 'r') as f:- assert f.read() == 'hello world'---@patch('openhands.resolver.interfaces.github.GithubIssueHandler.reply_to_comment')-@patch('httpx.post')-@patch('subprocess.run')-@patch('openhands.resolver.send_pull_request.LLM')-def test_update_existing_pull_request(- mock_llm_class,- mock_subprocess_run,- mock_requests_post,- mock_reply_to_comment,-):- # Arrange: Set up test data- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='This is a test PR',- thread_ids=['comment1', 'comment2'],- head_branch='test-branch',- )- token = 'test-token'- username = 'test-user'- patch_dir = '/path/to/patch'- additional_message = '["Fixed bug in function A", "Updated documentation for B"]'-- # Mock the subprocess.run call for git push- mock_subprocess_run.return_value = MagicMock(returncode=0)-- # Mock the requests.post call for adding a PR comment- mock_requests_post.return_value.status_code = 201-- # Mock LLM instance and completion call- mock_llm_instance = MagicMock()- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(message=MagicMock(content='This is an issue resolution.'))- ]- mock_llm_instance.completion.return_value = mock_completion_response- mock_llm_class.return_value = mock_llm_instance-- llm_config = LLMConfig()-- # Act: Call the function without comment_message to test auto-generation- result = update_existing_pull_request(- issue,- token,- username,- ProviderType.GITHUB,- patch_dir,- llm_config,- comment_message=None,- additional_message=additional_message,- )-- # Assert: Check if the git push command was executed- push_command = (- f'git -C {patch_dir} push '- f'https://{username}:{token}@github.com/'- f'{issue.owner}/{issue.repo}.git {issue.head_branch}'- )- mock_subprocess_run.assert_called_once_with(- push_command, shell=True, capture_output=True, text=True- )-- # Assert: Check if the auto-generated comment was posted to the PR- comment_url = f'https://api.github.com/repos/{issue.owner}/{issue.repo}/issues/{issue.number}/comments'- expected_comment = 'This is an issue resolution.'- mock_requests_post.assert_called_once_with(- comment_url,- headers={- 'Authorization': f'token {token}',- 'Accept': 'application/vnd.github.v3+json',- },- json={'body': expected_comment},- )-- # Assert: Check if the reply_to_comment function was called for each thread ID- mock_reply_to_comment.assert_has_calls(- [- call(issue.number, 'comment1', 'Fixed bug in function A'),- call(issue.number, 'comment2', 'Updated documentation for B'),- ]- )-- # Assert: Check the returned PR URL- assert (- result == f'https://github.com/{issue.owner}/{issue.repo}/pull/{issue.number}'- )--- 'pr_type,target_branch,pr_title',- [- ('branch', None, None),- ('draft', None, None),- ('ready', None, None),- ('branch', 'feature', None),- ('draft', 'develop', None),- ('ready', 'staging', None),- ('ready', None, 'Custom PR Title'),- ('draft', 'develop', 'Another Custom Title'),- ],-)-@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request(- mock_get,- mock_post,- mock_run,- mock_issue,- mock_llm_config,- mock_output_dir,- pr_type,- target_branch,- pr_title,-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses based on whether target_branch is specified- if target_branch:- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(status_code=200), # Target branch exists- ]- else:- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- ]-- mock_post.return_value.json.return_value = {- 'html_url': 'https://github.com/test-owner/test-repo/pull/1'- }-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function- result = send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type=pr_type,- target_branch=target_branch,- pr_title=pr_title,- )-- # Assert API calls- expected_get_calls = 2- assert mock_get.call_count == expected_get_calls-- # Check branch creation and push- assert mock_run.call_count == 2- checkout_call, push_call = mock_run.call_args_list-- assert checkout_call == call(- ['git', '-C', repo_path, 'checkout', '-b', 'openhands-fix-issue-42'],- capture_output=True,- text=True,- )- assert push_call == call(- [- 'git',- '-C',- repo_path,- 'push',- 'https://test-user:[email protected]/test-owner/test-repo.git',- 'openhands-fix-issue-42',- ],- capture_output=True,- text=True,- )-- # Check PR creation based on pr_type- if pr_type == 'branch':- assert (- result- == 'https://github.com/test-owner/test-repo/compare/openhands-fix-issue-42?expand=1'- )- mock_post.assert_not_called()- else:- assert result == 'https://github.com/test-owner/test-repo/pull/1'- mock_post.assert_called_once()- post_data = mock_post.call_args[1]['json']- expected_title = pr_title if pr_title else 'Fix issue #42: Test Issue'- assert post_data['title'] == expected_title- assert post_data['body'].startswith('This pull request fixes #42.')- assert post_data['head'] == 'openhands-fix-issue-42'- assert post_data['base'] == (target_branch if target_branch else 'main')- assert post_data['draft'] == (pr_type == 'draft')---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request_with_reviewer(- mock_get, mock_post, mock_run, mock_issue, mock_output_dir, mock_llm_config-):- repo_path = os.path.join(mock_output_dir, 'repo')- reviewer = 'test-reviewer'-- # Mock API responses- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- ]-- # Mock PR creation response- mock_post.side_effect = [- MagicMock(- status_code=201,- json=lambda: {- 'html_url': 'https://github.com/test-owner/test-repo/pull/1',- 'number': 1,- },- ), # PR creation- MagicMock(status_code=201), # Reviewer request- ]-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function with reviewer- result = send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type='ready',- reviewer=reviewer,- )-- # Assert API calls- assert mock_get.call_count == 2- assert mock_post.call_count == 2-- # Check PR creation- pr_create_call = mock_post.call_args_list[0]- assert pr_create_call[1]['json']['title'] == 'Fix issue #42: Test Issue'-- # Check reviewer request- reviewer_request_call = mock_post.call_args_list[1]- assert (- reviewer_request_call[0][0]- == 'https://api.github.com/repos/test-owner/test-repo/pulls/1/requested_reviewers'- )- assert reviewer_request_call[1]['json'] == {'reviewers': ['test-reviewer']}-- # Check the result URL- assert result == 'https://github.com/test-owner/test-repo/pull/1'---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request_target_branch_with_fork(- mock_get, mock_post, mock_run, mock_issue, mock_output_dir-):- """Test that target_branch works correctly when using a fork."""- repo_path = os.path.join(mock_output_dir, 'repo')- fork_owner = 'fork-owner'- target_branch = 'custom-target'-- # Mock API responses- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(status_code=200), # Target branch exists- ]-- mock_post.return_value.json.return_value = {- 'html_url': 'https://github.com/test-owner/test-repo/pull/1'- }-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function with fork_owner and target_branch- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type='ready',- fork_owner=fork_owner,- target_branch=target_branch,- )-- # Assert API calls- assert mock_get.call_count == 2-- # Verify target branch was checked in original repo, not fork- target_branch_check = mock_get.call_args_list[1]- assert (- target_branch_check[0][0]- == f'https://api.github.com/repos/test-owner/test-repo/branches/{target_branch}'- )-- # Check PR creation- mock_post.assert_called_once()- post_data = mock_post.call_args[1]['json']- assert post_data['base'] == target_branch # PR should target the specified branch- assert (- post_data['head'] == 'fork-owner:openhands-fix-issue-42'- ) # Branch name should be standard-- # Check that push was to fork- push_call = mock_run.call_args_list[1]- assert f'https://test-user:[email protected]/{fork_owner}/test-repo.git' in str(- push_call- )---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request_target_branch_with_additional_message(- mock_get, mock_post, mock_run, mock_issue, mock_output_dir-):- """Test that target_branch works correctly with additional PR message."""- repo_path = os.path.join(mock_output_dir, 'repo')- target_branch = 'feature-branch'- additional_message = 'Additional PR context'-- # Mock API responses- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(status_code=200), # Target branch exists- ]-- mock_post.return_value.json.return_value = {- 'html_url': 'https://github.com/test-owner/test-repo/pull/1'- }-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function with target_branch and additional_message- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type='ready',- target_branch=target_branch,- additional_message=additional_message,- )-- # Assert API calls- assert mock_get.call_count == 2-- # Check PR creation- mock_post.assert_called_once()- post_data = mock_post.call_args[1]['json']- assert post_data['base'] == target_branch- assert additional_message in post_data['body']- assert 'This pull request fixes #42' in post_data['body']---@patch('httpx.get')-def test_send_pull_request_invalid_target_branch(- mock_get, mock_issue, mock_output_dir, mock_llm_config-):- """Test that an error is raised when specifying a non-existent target branch"""- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API response for non-existent branch- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(status_code=404), # Target branch doesn't exist- ]-- # Test that ValueError is raised when target branch doesn't exist- with pytest.raises(- ValueError, match='Target branch nonexistent-branch does not exist'- ):- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type='ready',- target_branch='nonexistent-branch',- )-- # Verify API calls- assert mock_get.call_count == 2---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request_git_push_failure(- mock_get, mock_post, mock_run, mock_issue, mock_output_dir, mock_llm_config-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses- mock_get.return_value = MagicMock(json=lambda: {'default_branch': 'main'})-- # Mock the subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=1, stderr='Error: failed to push some refs'), # git push- ]-- # Test that RuntimeError is raised when git push fails- with pytest.raises(- RuntimeError, match='Failed to push changes to the remote repository'- ):- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type='ready',- )-- # Assert that subprocess.run was called twice- assert mock_run.call_count == 2-- # Check the git checkout -b command- checkout_call = mock_run.call_args_list[0]- assert checkout_call[0][0] == [- 'git',- '-C',- repo_path,- 'checkout',- '-b',- 'openhands-fix-issue-42',- ]-- # Check the git push command- push_call = mock_run.call_args_list[1]- assert push_call[0][0] == [- 'git',- '-C',- repo_path,- 'push',- 'https://test-user:[email protected]/test-owner/test-repo.git',- 'openhands-fix-issue-42',- ]-- # Assert that no pull request was created- mock_post.assert_not_called()---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request_permission_error(- mock_get, mock_post, mock_run, mock_issue, mock_output_dir, mock_llm_config-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses- mock_get.return_value = MagicMock(json=lambda: {'default_branch': 'main'})- mock_post.return_value.status_code = 403-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Test that RuntimeError is raised when PR creation fails due to permissions- with pytest.raises(- RuntimeError, match='Failed to create pull request due to missing permissions.'- ):- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type='ready',- )-- # Assert that the branch was created and pushed- assert mock_run.call_count == 2- mock_post.assert_called_once()---@patch('httpx.post')-def test_reply_to_comment(mock_post, mock_issue):- # Arrange: set up the test data- token = 'test_token'- comment_id = 'test_comment_id'- reply = 'This is a test reply.'-- # Create an instance of GithubIssueHandler- handler = GithubIssueHandler(- owner='test-owner', repo='test-repo', token=token, username='test-user'- )-- # Mock the response from the GraphQL API- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {- 'data': {- 'addPullRequestReviewThreadReply': {- 'comment': {- 'id': 'test_reply_id',- 'body': 'Openhands fix success summary\n\n\nThis is a test reply.',- 'createdAt': '2024-10-01T12:34:56Z',- }- }- }- }-- mock_post.return_value = mock_response-- # Act: call the function- handler.reply_to_comment(mock_issue.number, comment_id, reply)-- # Assert: check that the POST request was made with the correct parameters- query = """- mutation($body: String!, $pullRequestReviewThreadId: ID!) {- addPullRequestReviewThreadReply(input: { body: $body, pullRequestReviewThreadId: $pullRequestReviewThreadId }) {- comment {- id- body- createdAt- }- }- }- """-- expected_variables = {- 'body': 'Openhands fix success summary\n\n\nThis is a test reply.',- 'pullRequestReviewThreadId': comment_id,- }-- # Check that the correct request was made to the API- mock_post.assert_called_once_with(- 'https://api.github.com/graphql',- json={'query': query, 'variables': expected_variables},- headers={- 'Authorization': f'Bearer {token}',- 'Content-Type': 'application/json',- },- )-- # Check that the response status was checked (via response.raise_for_status)- mock_response.raise_for_status.assert_called_once()---@patch('openhands.resolver.send_pull_request.initialize_repo')-@patch('openhands.resolver.send_pull_request.apply_patch')-@patch('openhands.resolver.send_pull_request.update_existing_pull_request')-@patch('openhands.resolver.send_pull_request.make_commit')-def test_process_single_pr_update(- mock_make_commit,- mock_update_existing_pull_request,- mock_apply_patch,- mock_initialize_repo,- mock_output_dir,- mock_llm_config,-):- # Initialize test data- token = 'test_token'- username = 'test_user'- pr_type = 'draft'-- resolver_output = ResolverOutput(- issue=Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Issue 1',- body='Body 1',- closing_issues=[],- review_threads=[- ReviewThread(comment='review comment for feedback', files=[])- ],- thread_ids=['1'],- head_branch='branch 1',- ),- issue_type='pr',- instruction='Test instruction 1',- base_commit='def456',- git_patch='Test patch 1',- history=[],- metrics={},- success=True,- comment_success=None,- result_explanation='[Test success 1]',- error=None,- )-- mock_update_existing_pull_request.return_value = (- 'https://github.com/test-owner/test-repo/pull/1'- )- mock_initialize_repo.return_value = f'{mock_output_dir}/patches/pr_1'-- process_single_issue(- mock_output_dir,- resolver_output,- token,- username,- ProviderType.GITHUB,- pr_type,- mock_llm_config,- None,- False,- None,- )-- mock_initialize_repo.assert_called_once_with(mock_output_dir, 1, 'pr', 'branch 1')- mock_apply_patch.assert_called_once_with(- f'{mock_output_dir}/patches/pr_1', resolver_output.git_patch- )- mock_make_commit.assert_called_once_with(- f'{mock_output_dir}/patches/pr_1',- resolver_output.issue,- 'pr',- 'openhands',- '[email protected]',- )- mock_update_existing_pull_request.assert_called_once_with(- issue=resolver_output.issue,- token=token,- username=username,- platform=ProviderType.GITHUB,- patch_dir=f'{mock_output_dir}/patches/pr_1',- additional_message='[Test success 1]',- llm_config=mock_llm_config,- base_domain='github.com',- )---@patch('openhands.resolver.send_pull_request.initialize_repo')-@patch('openhands.resolver.send_pull_request.apply_patch')-@patch('openhands.resolver.send_pull_request.send_pull_request')-@patch('openhands.resolver.send_pull_request.make_commit')-def test_process_single_issue(- mock_make_commit,- mock_send_pull_request,- mock_apply_patch,- mock_initialize_repo,- mock_output_dir,- mock_llm_config,-):- # Initialize test data- token = 'test_token'- username = 'test_user'- pr_type = 'draft'- platform = ProviderType.GITHUB-- resolver_output = ResolverOutput(- issue=Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Issue 1',- body='Body 1',- ),- issue_type='issue',- instruction='Test instruction 1',- base_commit='def456',- git_patch='Test patch 1',- history=[],- metrics={},- success=True,- comment_success=None,- result_explanation='Test success 1',- error=None,- )-- # Mock return value- mock_send_pull_request.return_value = (- 'https://github.com/test-owner/test-repo/pull/1'- )- mock_initialize_repo.return_value = f'{mock_output_dir}/patches/issue_1'-- # Call the function- process_single_issue(- mock_output_dir,- resolver_output,- token,- username,- platform,- pr_type,- mock_llm_config,- None,- False,- None,- )-- # Assert that the mocked functions were called with correct arguments- mock_initialize_repo.assert_called_once_with(mock_output_dir, 1, 'issue', 'def456')- mock_apply_patch.assert_called_once_with(- f'{mock_output_dir}/patches/issue_1', resolver_output.git_patch- )- mock_make_commit.assert_called_once_with(- f'{mock_output_dir}/patches/issue_1',- resolver_output.issue,- 'issue',- 'openhands',- '[email protected]',- )- mock_send_pull_request.assert_called_once_with(- issue=resolver_output.issue,- token=token,- username=username,- platform=platform,- patch_dir=f'{mock_output_dir}/patches/issue_1',- pr_type=pr_type,- fork_owner=None,- additional_message=resolver_output.result_explanation,- target_branch=None,- reviewer=None,- pr_title=None,- base_domain='github.com',- git_user_name='openhands',- git_user_email='[email protected]',- )---@patch('openhands.resolver.send_pull_request.initialize_repo')-@patch('openhands.resolver.send_pull_request.apply_patch')-@patch('openhands.resolver.send_pull_request.send_pull_request')-@patch('openhands.resolver.send_pull_request.make_commit')-def test_process_single_issue_unsuccessful(- mock_make_commit,- mock_send_pull_request,- mock_apply_patch,- mock_initialize_repo,- mock_output_dir,- mock_llm_config,-):- # Initialize test data- token = 'test_token'- username = 'test_user'- pr_type = 'draft'-- resolver_output = ResolverOutput(- issue=Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Issue 1',- body='Body 1',- ),- issue_type='issue',- instruction='Test instruction 1',- base_commit='def456',- git_patch='Test patch 1',- history=[],- metrics={},- success=False,- comment_success=None,- result_explanation='',- error='Test error',- )-- # Call the function- process_single_issue(- mock_output_dir,- resolver_output,- token,- username,- ProviderType.GITHUB,- pr_type,- mock_llm_config,- None,- False,- None,- )-- # Assert that none of the mocked functions were called- mock_initialize_repo.assert_not_called()- mock_apply_patch.assert_not_called()- mock_make_commit.assert_not_called()- mock_send_pull_request.assert_not_called()---@patch('httpx.get')-@patch('subprocess.run')-def test_send_pull_request_branch_naming(- mock_run, mock_get, mock_issue, mock_output_dir, mock_llm_config-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses- mock_get.side_effect = [- MagicMock(status_code=200), # First branch exists- MagicMock(status_code=200), # Second branch exists- MagicMock(status_code=404), # Third branch doesn't exist- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- ]-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function- result = send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=repo_path,- pr_type='branch',- )-- # Assert API calls- assert mock_get.call_count == 4-- # Check branch creation and push- assert mock_run.call_count == 2- checkout_call, push_call = mock_run.call_args_list-- assert checkout_call == call(- ['git', '-C', repo_path, 'checkout', '-b', 'openhands-fix-issue-42-try3'],- capture_output=True,- text=True,- )- assert push_call == call(- [- 'git',- '-C',- repo_path,- 'push',- 'https://test-user:[email protected]/test-owner/test-repo.git',- 'openhands-fix-issue-42-try3',- ],- capture_output=True,- text=True,- )-- # Check the result- assert (- result- == 'https://github.com/test-owner/test-repo/compare/openhands-fix-issue-42-try3?expand=1'- )---@patch('openhands.resolver.send_pull_request.argparse.ArgumentParser')-@patch('openhands.resolver.send_pull_request.process_single_issue')-@patch('openhands.resolver.send_pull_request.load_single_resolver_output')-@patch('openhands.resolver.send_pull_request.identify_token')-@patch('os.path.exists')-@patch('os.getenv')-def test_main(- mock_getenv,- mock_path_exists,- mock_identify_token,- mock_load_single_resolver_output,- mock_process_single_issue,- mock_parser,-):- # Setup mock parser- mock_args = MagicMock()- mock_args.token = None- mock_args.username = 'mock_username'- mock_args.output_dir = '/mock/output'- mock_args.pr_type = 'draft'- mock_args.issue_number = '42'- mock_args.fork_owner = None- mock_args.send_on_failure = False- mock_args.llm_model = 'mock_model'- mock_args.llm_base_url = 'mock_url'- mock_args.llm_api_key = 'mock_key'- mock_args.target_branch = None- mock_args.reviewer = None- mock_args.pr_title = None- mock_args.selected_repo = None- mock_parser.return_value.parse_args.return_value = mock_args-- # Setup environment variables- mock_getenv.side_effect = (- lambda key, default=None: 'mock_token' if key == 'GITHUB_TOKEN' else default- )-- # Setup path exists- mock_path_exists.return_value = True-- # Setup mock resolver output- mock_resolver_output = MagicMock()- mock_load_single_resolver_output.return_value = mock_resolver_output-- mock_identify_token.return_value = ProviderType.GITHUB-- # Run main function- main()-- mock_identify_token.assert_called_with('mock_token', mock_args.base_domain)-- llm_config = LLMConfig(- model=mock_args.llm_model,- base_url=mock_args.llm_base_url,- api_key=mock_args.llm_api_key,- )-- # Use any_call instead of assert_called_with for more flexible matching- assert mock_process_single_issue.call_args == call(- '/mock/output',- mock_resolver_output,- 'mock_token',- 'mock_username',- ProviderType.GITHUB,- 'draft',- llm_config,- None,- False,- mock_args.target_branch,- mock_args.reviewer,- mock_args.pr_title,- ANY,- ANY, # git_user_name from args- ANY, # git_user_email from args- )-- # Other assertions- mock_parser.assert_called_once()- mock_getenv.assert_any_call('GITHUB_TOKEN')- mock_path_exists.assert_called_with('/mock/output')- mock_load_single_resolver_output.assert_called_with('/mock/output/output.jsonl', 42)-- # Test for invalid issue number- mock_args.issue_number = 'invalid'- with pytest.raises(ValueError):- main()-- # Test for invalid token- mock_args.issue_number = '42' # Reset to valid issue number- mock_getenv.side_effect = (- lambda key, default=None: None- ) # Return None for all env vars- with pytest.raises(ValueError, match='token is not set'):- main()---@patch('subprocess.run')-def test_make_commit_escapes_issue_title(mock_subprocess_run):- # Setup- repo_dir = '/path/to/repo'- issue = Issue(- owner='test-owner',- repo='test-repo',- number=42,- title='Issue with "quotes" and $pecial characters',- body='Test body',- )-- # Mock subprocess.run to return success for all calls- mock_subprocess_run.return_value = MagicMock(- returncode=0, stdout='sample output', stderr=''- )-- # Call the function- issue_type = 'issue'- make_commit(repo_dir, issue, issue_type)-- # Assert that subprocess.run was called with the correct arguments- calls = mock_subprocess_run.call_args_list- assert len(calls) == 4 # git config check, git add, git commit-- # Check the git commit call- git_commit_call = calls[3][0][0]- expected_commit_message = (- 'Fix issue #42: Issue with "quotes" and $pecial characters'- )- assert [- 'git',- '-C',- '/path/to/repo',- 'commit',- '-m',- expected_commit_message,- ] == git_commit_call---@patch('subprocess.run')-def test_make_commit_no_changes(mock_subprocess_run):- # Setup- repo_dir = '/path/to/repo'- issue = Issue(- owner='test-owner',- repo='test-repo',- number=42,- title='Issue with no changes',- body='Test body',- )-- # Mock subprocess.run to simulate no changes in the repo- mock_subprocess_run.side_effect = [- MagicMock(returncode=0),- MagicMock(returncode=0),- MagicMock(returncode=1, stdout=''), # git status --porcelain (no changes)- ]-- with pytest.raises(- RuntimeError, match='ERROR: Openhands failed to make code changes.'- ):- make_commit(repo_dir, issue, 'issue')-- # Check that subprocess.run was called for checking git status and add, but not commit- assert mock_subprocess_run.call_count == 3- git_status_call = mock_subprocess_run.call_args_list[2][0][0]- assert f'git -C {repo_dir} status --porcelain' in git_status_call---@patch('subprocess.run')-def test_make_commit_with_custom_git_config(mock_subprocess_run):- # Setup- repo_dir = '/path/to/repo'- issue = Issue(- owner='test-owner',- repo='test-repo',- number=42,- title='Test Issue',- body='Test body',- )- custom_git_user_name = 'custom-user'- custom_git_user_email = '[email protected]'-- # Mock subprocess.run to simulate successful operations- mock_subprocess_run.side_effect = [- MagicMock(- returncode=0, stdout=''- ), # git config user.name check (empty = not set)- MagicMock(returncode=0), # git config set user.name and user.email- MagicMock(returncode=0), # git add- MagicMock(returncode=0, stdout='modified files'), # git status --porcelain- MagicMock(returncode=0), # git commit- ]-- # Call the function with custom git config- make_commit(repo_dir, issue, 'issue', custom_git_user_name, custom_git_user_email)-- # Assert that subprocess.run was called with the correct arguments- calls = mock_subprocess_run.call_args_list- assert len(calls) == 5-- # Check git config check call (first call)- git_config_check_call = calls[0][0][0]- assert git_config_check_call == f'git -C {repo_dir} config user.name'-- # Check git config set call (second call)- git_config_set_call = calls[1][0][0]- expected_config_command = (- f'git -C {repo_dir} config user.name "{custom_git_user_name}" && '- f'git -C {repo_dir} config user.email "{custom_git_user_email}" && '- f'git -C {repo_dir} config alias.git "git --no-pager"'- )- assert expected_config_command == git_config_set_call---@patch('subprocess.run')-def test_make_commit_with_existing_git_config(mock_subprocess_run):- # Setup- repo_dir = '/path/to/repo'- issue = Issue(- owner='test-owner',- repo='test-repo',- number=42,- title='Test Issue',- body='Test body',- )-- # Mock subprocess.run to simulate successful operations- mock_subprocess_run.side_effect = [- MagicMock(- returncode=0, stdout='existing-user\n'- ), # git config user.name check (non-empty = already set)- MagicMock(returncode=0), # git add- MagicMock(returncode=0, stdout='modified files'), # git status --porcelain- MagicMock(returncode=0), # git commit- ]-- # Call the function- make_commit(repo_dir, issue, 'issue')-- # Assert that subprocess.run was called with the correct arguments- calls = mock_subprocess_run.call_args_list- assert len(calls) == 4-- # Check git config check call (first call)- git_config_check_call = calls[0][0][0]- assert git_config_check_call == f'git -C {repo_dir} config user.name'-- # Check that git config set was NOT called (since username already exists)- # The remaining calls should be git add, git status, git commit- git_add_call = calls[1][0][0]- assert f'git -C {repo_dir} add .' == git_add_call---@patch('subprocess.run')-def test_make_commit_with_special_characters_in_git_config(mock_subprocess_run):- # Setup- repo_dir = '/path/to/repo'- issue = Issue(- owner='test-owner',- repo='test-repo',- number=42,- title='Test Issue',- body='Test body',- )- git_user_name = 'User "with quotes"'- git_user_email = '[email protected]'-- # Mock subprocess.run to simulate successful operations- mock_subprocess_run.side_effect = [- MagicMock(- returncode=0, stdout=''- ), # git config user.name check (empty = not set)- MagicMock(returncode=0), # git config set- MagicMock(returncode=0), # git add- MagicMock(returncode=0, stdout='modified files'), # git status --porcelain- MagicMock(returncode=0), # git commit- ]-- # Call the function with special characters in git config- make_commit(repo_dir, issue, 'issue', git_user_name, git_user_email)-- # Assert that subprocess.run was called with properly escaped git config- calls = mock_subprocess_run.call_args_list- assert len(calls) == 5-- # Check git config check call (first call)- git_config_check_call = calls[0][0][0]- assert git_config_check_call == f'git -C {repo_dir} config user.name'-- # Check git config set call (second call)- git_config_set_call = calls[1][0][0]-- # Check that quotes are properly handled in the command- expected_config_command = (- f'git -C {repo_dir} config user.name "{git_user_name}" && '- f'git -C {repo_dir} config user.email "{git_user_email}" && '- f'git -C {repo_dir} config alias.git "git --no-pager"'- )- assert expected_config_command == git_config_set_call---def test_apply_patch_rename_directory(mock_output_dir):- # Create a sample directory structure- old_dir = os.path.join(mock_output_dir, 'prompts', 'resolve')- os.makedirs(old_dir)-- # Create test files- test_files = [- 'issue-success-check.jinja',- 'pr-feedback-check.jinja',- 'pr-thread-check.jinja',- ]- for filename in test_files:- file_path = os.path.join(old_dir, filename)- with open(file_path, 'w') as f:- f.write(f'Content of {filename}')-- # Create a patch that renames the directory- patch_content = """diff --git a/prompts/resolve/issue-success-check.jinja b/prompts/guess_success/issue-success-check.jinja-similarity index 100%-rename from prompts/resolve/issue-success-check.jinja-rename to prompts/guess_success/issue-success-check.jinja-diff --git a/prompts/resolve/pr-feedback-check.jinja b/prompts/guess_success/pr-feedback-check.jinja-similarity index 100%-rename from prompts/resolve/pr-feedback-check.jinja-rename to prompts/guess_success/pr-feedback-check.jinja-diff --git a/prompts/resolve/pr-thread-check.jinja b/prompts/guess_success/pr-thread-check.jinja-similarity index 100%-rename from prompts/resolve/pr-thread-check.jinja-rename to prompts/guess_success/pr-thread-check.jinja"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if files were moved correctly- new_dir = os.path.join(mock_output_dir, 'prompts', 'guess_success')- assert not os.path.exists(old_dir), 'Old directory still exists'- assert os.path.exists(new_dir), 'New directory was not created'-- # Check if all files were moved and content preserved- for filename in test_files:- old_path = os.path.join(old_dir, filename)- new_path = os.path.join(new_dir, filename)- assert not os.path.exists(old_path), f'Old file {filename} still exists'- assert os.path.exists(new_path), f'New file {filename} was not created'- with open(new_path, 'r') as f:- content = f.read()- assert content == f'Content of {filename}', f'Content mismatch for {filename}'diff --git a/tests/unit/resolver/gitlab/test_gitlab_guess_success.py b/tests/unit/resolver/gitlab/test_gitlab_guess_success.pydeleted file mode 100644index 9c4991c091..0000000000--- a/tests/unit/resolver/gitlab/test_gitlab_guess_success.py+++ /dev/null@@ -1,202 +0,0 @@-import json-from unittest.mock import MagicMock, patch--from openhands.core.config import LLMConfig-from openhands.events.action.message import MessageAction-from openhands.llm import LLM-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandler-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)---def test_guess_success_multiline_explanation():- # Mock data- issue = Issue(- owner='test',- repo='test',- number=1,- title='Test Issue',- body='Test body',- thread_comments=None,- review_comments=None,- )- history = [MessageAction(content='Test message')]- llm_config = LLMConfig(model='test', api_key='test')-- # Create a mock response with multi-line explanation- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The PR successfully addressed the issue by:-- Fixed bug A-- Added test B-- Updated documentation C--Automatic fix generated by OpenHands π"""- )- )- ]-- # Use patch to mock the LLM completion call- with patch.object(LLM, 'completion', return_value=mock_response) as mock_completion:- # Create a handler instance- handler = ServiceContextIssue(- GitlabIssueHandler('test', 'test', 'test'), llm_config- )-- # Call guess_success- success, _, explanation = handler.guess_success(issue, history)-- # Verify the results- assert success is True- assert 'The PR successfully addressed the issue by:' in explanation- assert 'Fixed bug A' in explanation- assert 'Added test B' in explanation- assert 'Updated documentation C' in explanation- assert 'Automatic fix generated by OpenHands' in explanation-- # Verify that LLM completion was called exactly once- mock_completion.assert_called_once()---def test_pr_handler_guess_success_with_thread_comments():- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(GitlabPRHandler('test', 'test', 'test'), llm_config)-- # Create a mock issue with thread comments but no review comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=['First comment', 'Second comment'],- closing_issues=['Issue description'],- review_comments=None,- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history- history = [MessageAction(content='Fixed the issue by implementing X and Y')]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion', return_value=mock_response):- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the results- assert success is True- assert success_list == [True]- assert 'successfully address' in explanation- assert len(json.loads(explanation)) == 1---def test_pr_handler_guess_success_only_review_comments():- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with only review comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue description'],- review_comments=['Please fix the formatting', 'Add more tests'],- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history- history = [MessageAction(content='Fixed the formatting and added more tests')]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the review comments."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion', return_value=mock_response):- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the results- assert success is True- assert success_list == [True]- assert (- '["The changes successfully address the review comments."]' in explanation- )---def test_pr_handler_guess_success_no_comments():- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(GitlabPRHandler('test', 'test', 'test'), llm_config)-- # Create a mock issue with no comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue description'],- review_comments=None,- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history- history = [MessageAction(content='Fixed the issue')]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Test that it returns appropriate message when no comments are present- success, success_list, explanation = handler.guess_success(issue, history)- assert success is False- assert success_list is None- assert explanation == 'No feedback was found to process'diff --git a/tests/unit/resolver/gitlab/test_gitlab_issue_handler.py b/tests/unit/resolver/gitlab/test_gitlab_issue_handler.pydeleted file mode 100644index 1dda6f9235..0000000000--- a/tests/unit/resolver/gitlab/test_gitlab_issue_handler.py+++ /dev/null@@ -1,683 +0,0 @@-from unittest.mock import MagicMock, patch--from openhands.core.config import LLMConfig-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandler-from openhands.resolver.interfaces.issue import ReviewThread-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)---def test_get_converted_issues_initializes_review_comments():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for issues- mock_issues_response = MagicMock()- mock_issues_response.json.return_value = [- {'iid': 1, 'title': 'Test Issue', 'description': 'Test Body'}- ]- # Mock the response for comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = []-- # Set up the mock to return different responses for different calls- # First call is for issues, second call is for comments- mock_get.side_effect = [- mock_issues_response,- mock_comments_response,- mock_comments_response,- ] # Need two comment responses because we make two API calls-- # Create an instance of IssueHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GitlabIssueHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- issues = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one issue- assert len(issues) == 1-- # Verify that review_comments is initialized as None- assert issues[0].review_comments is None-- # Verify other fields are set correctly- assert issues[0].number == 1- assert issues[0].title == 'Test Issue'- assert issues[0].body == 'Test Body'- assert issues[0].owner == 'test-owner'- assert issues[0].repo == 'test-repo'---def test_get_converted_issues_handles_empty_body():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for issues- mock_issues_response = MagicMock()- mock_issues_response.json.return_value = [- {'iid': 1, 'title': 'Test Issue', 'description': None}- ]- # Mock the response for comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = []- # Set up the mock to return different responses- mock_get.side_effect = [- mock_issues_response,- mock_comments_response,- mock_comments_response,- ]-- # Create an instance of IssueHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GitlabIssueHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- issues = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one issue- assert len(issues) == 1-- # Verify that body is empty string when None- assert issues[0].body == ''-- # Verify other fields are set correctly- assert issues[0].number == 1- assert issues[0].title == 'Test Issue'- assert issues[0].owner == 'test-owner'- assert issues[0].repo == 'test-repo'-- # Verify that review_comments is initialized as None- assert issues[0].review_comments is None---def test_pr_handler_get_converted_issues_with_comments():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'iid': 1,- 'title': 'Test PR',- 'description': 'Test Body fixes #1',- 'source_branch': 'test-branch',- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'body': 'First comment', 'resolvable': True, 'system': False},- {'body': 'Second comment', 'resolvable': True, 'system': False},- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'project': {- 'mergeRequest': {- 'discussions': {'edges': []},- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- # Mock the response for fetching the external issue referenced in PR body- mock_external_issue_response = MagicMock()- mock_external_issue_response.json.return_value = {- 'description': 'This is additional context from an externally referenced issue.'- }-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_empty_response, # Third call for related issues- mock_comments_response, # Fourth call for PR comments- mock_empty_response, # Fifth call for PR comments (empty page)- mock_external_issue_response, # Mock response for the external issue reference #1- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments == ['First comment', 'Second comment']-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body fixes #1'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'- assert prs[0].closing_issues == [- 'This is additional context from an externally referenced issue.'- ]---def test_get_issue_comments_with_specific_comment_id():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'id': 123, 'body': 'First comment', 'resolvable': True, 'system': False},- {'id': 456, 'body': 'Second comment', 'resolvable': True, 'system': False},- ]-- mock_get.return_value = mock_comments_response-- # Create an instance of IssueHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GitlabIssueHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get comments with a specific comment_id- specific_comment = handler.get_issue_comments(issue_number=1, comment_id=123)-- # Verify only the specific comment is returned- assert specific_comment == ['First comment']---def test_pr_handler_get_converted_issues_with_specific_thread_comment():- # Define the specific comment_id to filter- specific_comment_id = 123-- # Mock GraphQL response for review threads- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'iid': 1,- 'title': 'Test PR',- 'description': 'Test Body',- 'source_branch': 'test-branch',- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {'body': 'First comment', 'id': 123, 'resolvable': True, 'system': False},- {'body': 'Second comment', 'id': 124, 'resolvable': True, 'system': False},- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'project': {- 'mergeRequest': {- 'discussions': {- 'edges': [- {- 'node': {- 'id': 'review-thread-1',- 'resolved': False,- 'resolvable': True,- 'notes': {- 'nodes': [- {- 'id': 'GID/121',- 'body': 'Specific review comment',- 'position': {- 'filePath': 'file1.txt',- },- },- {- 'id': 'GID/456',- 'body': 'Another review comment',- 'position': {- 'filePath': 'file2.txt',- },- },- ]- },- }- }- ]- },- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_empty_response, # Third call for related issues- mock_comments_response, # Fourth call for PR comments- mock_empty_response, # Fifth call for PR comments (empty page)- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments == ['First comment']- assert prs[0].review_comments is None- assert prs[0].review_threads == []-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'---def test_pr_handler_get_converted_issues_with_specific_review_thread_comment():- # Define the specific comment_id to filter- specific_comment_id = 123-- # Mock GraphQL response for review threads- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'iid': 1,- 'title': 'Test PR',- 'description': 'Test Body',- 'source_branch': 'test-branch',- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {- 'description': 'First comment',- 'id': 120,- 'resolvable': True,- 'system': False,- },- {- 'description': 'Second comment',- 'id': 124,- 'resolvable': True,- 'system': False,- },- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'project': {- 'mergeRequest': {- 'discussions': {- 'edges': [- {- 'node': {- 'id': 'review-thread-1',- 'resolved': False,- 'resolvable': True,- 'notes': {- 'nodes': [- {- 'id': f'GID/{specific_comment_id}',- 'body': 'Specific review comment',- 'position': {- 'filePath': 'file1.txt',- },- },- {- 'id': 'GID/456',- 'body': 'Another review comment',- 'position': {- 'filePath': 'file1.txt',- },- },- ]- },- }- }- ]- },- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_empty_response, # Third call for related issues- mock_comments_response, # Fourth call for PR comments- mock_empty_response, # Fifth call for PR comments (empty page)- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments is None- assert prs[0].review_comments is None- assert len(prs[0].review_threads) == 1- assert isinstance(prs[0].review_threads[0], ReviewThread)- assert (- prs[0].review_threads[0].comment- == 'Specific review comment\n---\nlatest feedback:\nAnother review comment\n'- )- assert prs[0].review_threads[0].files == ['file1.txt']-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'---def test_pr_handler_get_converted_issues_with_specific_comment_and_issue_refs():- # Define the specific comment_id to filter- specific_comment_id = 123-- # Mock GraphQL response for review threads- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'iid': 1,- 'title': 'Test PR fixes #3',- 'description': 'Test Body',- 'source_branch': 'test-branch',- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {- 'description': 'First comment',- 'id': 120,- 'resolvable': True,- 'system': False,- },- {- 'description': 'Second comment',- 'id': 124,- 'resolvable': True,- 'system': False,- },- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'project': {- 'mergeRequest': {- 'discussions': {- 'edges': [- {- 'node': {- 'id': 'review-thread-1',- 'resolved': False,- 'resolvable': True,- 'notes': {- 'nodes': [- {- 'id': f'GID/{specific_comment_id}',- 'body': 'Specific review comment that references #6',- 'position': {- 'filePath': 'file1.txt',- },- },- {- 'id': 'GID/456',- 'body': 'Another review comment referencing #7',- 'position': {- 'filePath': 'file2.txt',- },- },- ]- },- }- }- ]- },- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- # Mock the response for fetching the external issue referenced in PR body- mock_external_issue_response_in_body = MagicMock()- mock_external_issue_response_in_body.json.return_value = {- 'description': 'External context #1.'- }-- # Mock the response for fetching the external issue referenced in review thread- mock_external_issue_response_review_thread = MagicMock()- mock_external_issue_response_review_thread.json.return_value = {- 'description': 'External context #2.'- }-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_empty_response, # Third call for related issues- mock_comments_response, # Fourth call for PR comments- mock_empty_response, # Fifth call for PR comments (empty page)- mock_external_issue_response_in_body,- mock_external_issue_response_review_thread,- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments is None- assert prs[0].review_comments is None- assert len(prs[0].review_threads) == 1- assert isinstance(prs[0].review_threads[0], ReviewThread)- assert (- prs[0].review_threads[0].comment- == 'Specific review comment that references #6\n---\nlatest feedback:\nAnother review comment referencing #7\n'- )- assert prs[0].closing_issues == [- 'External context #1.',- 'External context #2.',- ] # Only includes references inside comment ID and body PR-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR fixes #3'- assert prs[0].body == 'Test Body'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'---def test_pr_handler_get_converted_issues_with_duplicate_issue_refs():- # Mock the necessary dependencies- with patch('httpx.get') as mock_get:- # Mock the response for PRs- mock_prs_response = MagicMock()- mock_prs_response.json.return_value = [- {- 'iid': 1,- 'title': 'Test PR',- 'description': 'Test Body fixes #1',- 'source_branch': 'test-branch',- }- ]-- # Mock the response for PR comments- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {- 'body': 'First comment addressing #1',- 'resolvable': True,- 'system': False,- },- {- 'body': 'Second comment addressing #2',- 'resolvable': True,- 'system': False,- },- ]-- # Mock the response for PR metadata (GraphQL)- mock_graphql_response = MagicMock()- mock_graphql_response.json.return_value = {- 'data': {- 'project': {- 'mergeRequest': {- 'discussions': {'edges': []},- }- }- }- }-- # Set up the mock to return different responses- # We need to return empty responses for subsequent pages- mock_empty_response = MagicMock()- mock_empty_response.json.return_value = []-- # Mock the response for fetching the external issue referenced in PR body- mock_external_issue_response_in_body = MagicMock()- mock_external_issue_response_in_body.json.return_value = {- 'description': 'External context #1.'- }-- # Mock the response for fetching the external issue referenced in review thread- mock_external_issue_response_in_comment = MagicMock()- mock_external_issue_response_in_comment.json.return_value = {- 'description': 'External context #2.'- }-- mock_get.side_effect = [- mock_prs_response, # First call for PRs- mock_empty_response, # Second call for PRs (empty page)- mock_empty_response, # Third call for related issues- mock_comments_response, # Fourth call for PR comments- mock_empty_response, # Fifth call for PR comments (empty page)- mock_external_issue_response_in_body, # Mock response for the external issue reference #1- mock_external_issue_response_in_comment,- ]-- # Mock the post request for GraphQL- with patch('httpx.post') as mock_post:- mock_post.return_value = mock_graphql_response-- # Create an instance of PRHandler- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Get converted issues- prs = handler.get_converted_issues(issue_numbers=[1])-- # Verify that we got exactly one PR- assert len(prs) == 1-- # Verify that thread_comments are set correctly- assert prs[0].thread_comments == [- 'First comment addressing #1',- 'Second comment addressing #2',- ]-- # Verify other fields are set correctly- assert prs[0].number == 1- assert prs[0].title == 'Test PR'- assert prs[0].body == 'Test Body fixes #1'- assert prs[0].owner == 'test-owner'- assert prs[0].repo == 'test-repo'- assert prs[0].head_branch == 'test-branch'- assert prs[0].closing_issues == [- 'External context #1.',- 'External context #2.',- ]diff --git a/tests/unit/resolver/gitlab/test_gitlab_issue_handler_error_handling.py b/tests/unit/resolver/gitlab/test_gitlab_issue_handler_error_handling.pydeleted file mode 100644index 1dbd826376..0000000000--- a/tests/unit/resolver/gitlab/test_gitlab_issue_handler_error_handling.py+++ /dev/null@@ -1,280 +0,0 @@-from unittest.mock import MagicMock, patch--import httpx-import pytest-from litellm.exceptions import RateLimitError--from openhands.core.config import LLMConfig-from openhands.events.action.message import MessageAction-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandler-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)--[email protected](autouse=True)-def mock_logger(monkeypatch):- # suppress logging of completion data to file- mock_logger = MagicMock()- monkeypatch.setattr('openhands.llm.debug_mixin.llm_prompt_logger', mock_logger)- monkeypatch.setattr('openhands.llm.debug_mixin.llm_response_logger', mock_logger)- return mock_logger---def default_config():- return LLMConfig(- model='gpt-4o',- api_key='test_key',- num_retries=2,- retry_min_wait=1,- retry_max_wait=2,- )---def test_handle_nonexistent_issue_reference():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock the requests.get to simulate a 404 error- mock_response = MagicMock()- mock_response.raise_for_status.side_effect = httpx.HTTPError(- '404 Client Error: Not Found'- )-- with patch('httpx.get', return_value=mock_response):- # Call the method with a non-existent issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #999999', # Non-existent issue- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return an empty list since the referenced issue couldn't be fetched- assert result == []---def test_handle_rate_limit_error():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock the requests.get to simulate a rate limit error- mock_response = MagicMock()- mock_response.raise_for_status.side_effect = httpx.HTTPError(- '403 Client Error: Rate Limit Exceeded'- )-- with patch('httpx.get', return_value=mock_response):- # Call the method with an issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #123',- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return an empty list since the request was rate limited- assert result == []---def test_handle_network_error():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock the requests.get to simulate a network error- with patch('httpx.get', side_effect=httpx.NetworkError('Network Error')):- # Call the method with an issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #123',- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return an empty list since the network request failed- assert result == []---def test_successful_issue_reference():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Mock a successful response- mock_response = MagicMock()- mock_response.raise_for_status.return_value = None- mock_response.json.return_value = {- 'description': 'This is the referenced issue body'- }-- with patch('httpx.get', return_value=mock_response):- # Call the method with an issue reference- result = handler._strategy.get_context_from_external_issues_references(- closing_issues=[],- closing_issue_numbers=[],- issue_body='This references #123',- review_comments=[],- review_threads=[],- thread_comments=None,- )-- # The method should return a list with the referenced issue body- assert result == ['This is the referenced issue body']---class MockLLMResponse:- """Mock LLM Response class to mimic the actual LLM response structure."""-- class Choice:- class Message:- def __init__(self, content):- self.content = content-- def __init__(self, content):- self.message = self.Message(content)-- def __init__(self, content):- self.choices = [self.Choice(content)]---class DotDict(dict):- """A dictionary that supports dot notation access."""-- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- for key, value in self.items():- if isinstance(value, dict):- self[key] = DotDict(value)- elif isinstance(value, list):- self[key] = [- DotDict(item) if isinstance(item, dict) else item for item in value- ]-- def __getattr__(self, key):- if key in self:- return self[key]- else:- raise AttributeError(- f"'{self.__class__.__name__}' object has no attribute '{key}'"- )-- def __setattr__(self, key, value):- self[key] = value-- def __delattr__(self, key):- if key in self:- del self[key]- else:- raise AttributeError(- f"'{self.__class__.__name__}' object has no attribute '{key}'"- )---@patch('openhands.llm.llm.litellm_completion')-def test_guess_success_rate_limit_wait_time(mock_litellm_completion, default_config):- """Test that the retry mechanism in guess_success respects wait time between retries."""- with patch('time.sleep') as mock_sleep:- # Simulate a rate limit error followed by a successful response- mock_litellm_completion.side_effect = [- RateLimitError(- 'Rate limit exceeded', llm_provider='test_provider', model='test_model'- ),- DotDict(- {- 'choices': [- {- 'message': {- 'content': '--- success\ntrue\n--- explanation\nRetry successful'- }- }- ]- }- ),- ]-- llm = LLM(config=default_config, service_id='test-service')- handler = ServiceContextIssue(- GitlabIssueHandler('test-owner', 'test-repo', 'test-token'), default_config- )- handler.llm = llm-- # Mock issue and history- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test Issue',- body='This is a test issue.',- thread_comments=['Please improve error handling'],- )- history = [MessageAction(content='Fixed error handling.')]-- # Call guess_success- success, _, explanation = handler.guess_success(issue, history)-- # Assertions- assert success is True- assert explanation == 'Retry successful'- assert mock_litellm_completion.call_count == 2 # Two attempts made- mock_sleep.assert_called_once() # Sleep called once between retries-- # Validate wait time- wait_time = mock_sleep.call_args[0][0]- assert (- default_config.retry_min_wait <= wait_time <= default_config.retry_max_wait- ), (- f'Expected wait time between {default_config.retry_min_wait} and {default_config.retry_max_wait} seconds, but got {wait_time}'- )---@patch('openhands.llm.llm.litellm_completion')-def test_guess_success_exhausts_retries(mock_completion, default_config):- """Test the retry mechanism in guess_success exhausts retries and raises an error."""- # Simulate persistent rate limit errors by always raising RateLimitError- mock_completion.side_effect = RateLimitError(- 'Rate limit exceeded', llm_provider='test_provider', model='test_model'- )-- # Initialize LLM and handler- llm = LLM(config=default_config, service_id='test-service')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), default_config- )- handler.llm = llm-- # Mock issue and history- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test Issue',- body='This is a test issue.',- thread_comments=['Please improve error handling'],- )- history = [MessageAction(content='Fixed error handling.')]-- # Call guess_success and expect it to raise an error after retries- with pytest.raises(RateLimitError):- handler.guess_success(issue, history)-- # Assertions- assert (- mock_completion.call_count == default_config.num_retries- ) # Initial call + retriesdiff --git a/tests/unit/resolver/gitlab/test_gitlab_pr_handler_guess_success.py b/tests/unit/resolver/gitlab/test_gitlab_pr_handler_guess_success.pydeleted file mode 100644index a5596d7d76..0000000000--- a/tests/unit/resolver/gitlab/test_gitlab_pr_handler_guess_success.py+++ /dev/null@@ -1,672 +0,0 @@-import json-from unittest.mock import MagicMock, patch--import pytest--from openhands.core.config import LLMConfig-from openhands.events.action.message import MessageAction-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.gitlab import GitlabPRHandler-from openhands.resolver.interfaces.issue import Issue, ReviewThread-from openhands.resolver.interfaces.issue_definitions import ServiceContextPR---def pr_handler():- llm_config = LLMConfig(model='test-model')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )- return handler---def mock_llm_success_response():- return MagicMock(- choices=[- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes look good"""- )- )- ]- )---def test_guess_success_review_threads_litellm_call():- """Test that the completion() call for review threads contains the expected content."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with review threads- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue 1 description', 'Issue 2 description'],- review_comments=None,- review_threads=[- ReviewThread(- comment='Please fix the formatting\n---\nlatest feedback:\nAdd docstrings',- files=['/src/file1.py', '/src/file2.py'],- ),- ReviewThread(- comment='Add more tests\n---\nlatest feedback:\nAdd test cases',- files=['/tests/test_file.py'],- ),- ],- thread_ids=['1', '2'],- head_branch='test-branch',- )-- # Create mock history with a detailed response- history = [- MessageAction(- content="""I have made the following changes:-1. Fixed formatting in file1.py and file2.py-2. Added docstrings to all functions-3. Added test cases in test_file.py"""- )- ]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the completion() calls- assert mock_completion.call_count == 2 # One call per review thread-- # Check first call- first_call = mock_completion.call_args_list[0]- first_prompt = first_call[1]['messages'][0]['content']- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in first_prompt- )- assert (- 'Feedback:\nPlease fix the formatting\n---\nlatest feedback:\nAdd docstrings'- in first_prompt- )- assert (- 'Files locations:\n'- + json.dumps(['/src/file1.py', '/src/file2.py'], indent=4)- in first_prompt- )- assert 'Last message from AI agent:\n' + history[0].content in first_prompt-- # Check second call- second_call = mock_completion.call_args_list[1]- second_prompt = second_call[1]['messages'][0]['content']- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in second_prompt- )- assert (- 'Feedback:\nAdd more tests\n---\nlatest feedback:\nAdd test cases'- in second_prompt- )- assert (- 'Files locations:\n' + json.dumps(['/tests/test_file.py'], indent=4)- in second_prompt- )- assert 'Last message from AI agent:\n' + history[0].content in second_prompt-- assert len(json.loads(explanation)) == 2---def test_guess_success_thread_comments_litellm_call():- """Test that the completion() call for thread comments contains the expected content."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with thread comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=[- 'Please improve error handling',- 'Add input validation',- 'latest feedback:\nHandle edge cases',- ],- closing_issues=['Issue 1 description', 'Issue 2 description'],- review_comments=None,- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history with a detailed response- history = [- MessageAction(- content="""I have made the following changes:-1. Added try/catch blocks for error handling-2. Added input validation checks-3. Added handling for edge cases"""- )- ]-- # Create mock LLM config- llm_config = LLMConfig(model='test-model', api_key='test-key')-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- # Test the guess_success method- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in prompt- )- assert 'PR Thread Comments:\n' + '\n---\n'.join(issue.thread_comments) in prompt- assert 'Last message from AI agent:\n' + history[0].content in prompt-- assert len(json.loads(explanation)) == 1---def test_check_feedback_with_llm():- """Test the _check_feedback_with_llm helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Test cases for different LLM responses- test_cases = [- {- 'response': '--- success\ntrue\n--- explanation\nChanges look good',- 'expected': (True, 'Changes look good'),- },- {- 'response': '--- success\nfalse\n--- explanation\nNot all issues fixed',- 'expected': (False, 'Not all issues fixed'),- },- {- 'response': 'Invalid response format',- 'expected': (- False,- 'Failed to decode answer from LLM response: Invalid response format',- ),- },- {- 'response': '--- success\ntrue\n--- explanation\nMultiline\nexplanation\nhere',- 'expected': (True, 'Multiline\nexplanation\nhere'),- },- ]-- for case in test_cases:- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content=case['response']))]-- # Test the function- with patch.object(LLM, 'completion', return_value=mock_response):- success, explanation = handler._check_feedback_with_llm('test prompt')- assert (success, explanation) == case['expected']---def test_check_review_thread_with_git_patch():- """Test that git patch from complete_runtime is included in the prompt."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_thread = ReviewThread(- comment='Please fix the formatting\n---\nlatest feedback:\nAdd docstrings',- files=['/src/file1.py', '/src/file2.py'],- )- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have fixed the formatting and added docstrings'- git_patch = 'diff --git a/src/file1.py b/src/file1.py\n+"""Added docstring."""\n'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_thread(- review_thread, issues_context, last_message, git_patch- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'Feedback:\n' + review_thread.comment in prompt- assert (- 'Files locations:\n' + json.dumps(review_thread.files, indent=4) in prompt- )- assert 'Last message from AI agent:\n' + last_message in prompt- assert 'Changes made (git patch):\n' + git_patch in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_review_thread():- """Test the _check_review_thread helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_thread = ReviewThread(- comment='Please fix the formatting\n---\nlatest feedback:\nAdd docstrings',- files=['/src/file1.py', '/src/file2.py'],- )- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have fixed the formatting and added docstrings'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_thread(- review_thread, issues_context, last_message- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'Feedback:\n' + review_thread.comment in prompt- assert (- 'Files locations:\n' + json.dumps(review_thread.files, indent=4) in prompt- )- assert 'Last message from AI agent:\n' + last_message in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_thread_comments_with_git_patch():- """Test that git patch from complete_runtime is included in the prompt."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- thread_comments = [- 'Please improve error handling',- 'Add input validation',- 'latest feedback:\nHandle edge cases',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have added error handling and input validation'- git_patch = 'diff --git a/src/file1.py b/src/file1.py\n+try:\n+ validate_input()\n+except ValueError:\n+ handle_error()\n'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_thread_comments(- thread_comments, issues_context, last_message, git_patch- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Thread Comments:\n' + '\n---\n'.join(thread_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt- assert 'Changes made (git patch):\n' + git_patch in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_thread_comments():- """Test the _check_thread_comments helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- thread_comments = [- 'Please improve error handling',- 'Add input validation',- 'latest feedback:\nHandle edge cases',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have added error handling and input validation'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_thread_comments(- thread_comments, issues_context, last_message- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Thread Comments:\n' + '\n---\n'.join(thread_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_review_comments_with_git_patch():- """Test that git patch from complete_runtime is included in the prompt."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_comments = [- 'Please fix the code style',- 'Add more test cases',- 'latest feedback:\nImprove documentation',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have fixed the code style and added tests'- git_patch = 'diff --git a/src/file1.py b/src/file1.py\n+"""This module does X."""\n+def func():\n+ """Do Y."""\n'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_comments(- review_comments, issues_context, last_message, git_patch- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Review Comments:\n' + '\n---\n'.join(review_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt- assert 'Changes made (git patch):\n' + git_patch in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_check_review_comments():- """Test the _check_review_comments helper function."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create test data- review_comments = [- 'Please improve code readability',- 'Add comments to complex functions',- 'Follow PEP 8 style guide',- ]- issues_context = json.dumps(- ['Issue 1 description', 'Issue 2 description'], indent=4- )- last_message = 'I have improved code readability and added comments'-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-Changes look good"""- )- )- ]-- # Test the function- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, explanation = handler._check_review_comments(- review_comments, issues_context, last_message- )-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert 'Issue descriptions:\n' + issues_context in prompt- assert 'PR Review Comments:\n' + '\n---\n'.join(review_comments) in prompt- assert 'Last message from AI agent:\n' + last_message in prompt-- # Check result- assert success is True- assert explanation == 'Changes look good'---def test_guess_success_review_comments_litellm_call():- """Test that the completion() call for review comments contains the expected content."""- # Create a PR handler instance- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(- GitlabPRHandler('test-owner', 'test-repo', 'test-token'), llm_config- )-- # Create a mock issue with review comments- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='Test Body',- thread_comments=None,- closing_issues=['Issue 1 description', 'Issue 2 description'],- review_comments=[- 'Please improve code readability',- 'Add comments to complex functions',- 'Follow PEP 8 style guide',- ],- thread_ids=None,- head_branch='test-branch',- )-- # Create mock history with a detailed response- history = [- MessageAction(- content="""I have made the following changes:-1. Improved code readability by breaking down complex functions-2. Added detailed comments to all complex functions-3. Fixed code style to follow PEP 8"""- )- ]-- # Mock the LLM response- mock_response = MagicMock()- mock_response.choices = [- MagicMock(- message=MagicMock(- content="""--- success-true----- explanation-The changes successfully address the feedback."""- )- )- ]-- with patch.object(LLM, 'completion') as mock_completion:- mock_completion.return_value = mock_response- success, success_list, explanation = handler.guess_success(issue, history)-- # Verify the completion() call- mock_completion.assert_called_once()- call_args = mock_completion.call_args- prompt = call_args[1]['messages'][0]['content']-- # Check prompt content- assert (- 'Issue descriptions:\n'- + json.dumps(['Issue 1 description', 'Issue 2 description'], indent=4)- in prompt- )- assert 'PR Review Comments:\n' + '\n---\n'.join(issue.review_comments) in prompt- assert 'Last message from AI agent:\n' + history[0].content in prompt-- assert len(json.loads(explanation)) == 1diff --git a/tests/unit/resolver/gitlab/test_gitlab_pr_title_escaping.py b/tests/unit/resolver/gitlab/test_gitlab_pr_title_escaping.pydeleted file mode 100644index ea2b05b1d9..0000000000--- a/tests/unit/resolver/gitlab/test_gitlab_pr_title_escaping.py+++ /dev/null@@ -1,166 +0,0 @@-import os-import subprocess-import tempfile--from openhands.core.logger import openhands_logger as logger-from openhands.integrations.service_types import ProviderType-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.send_pull_request import make_commit, send_pull_request---def test_commit_message_with_quotes():- # Create a temporary directory and initialize git repo- with tempfile.TemporaryDirectory() as temp_dir:- subprocess.run(['git', 'init', temp_dir], check=True)-- # Create a test file and add it to git- test_file = os.path.join(temp_dir, 'test.txt')- with open(test_file, 'w') as f:- f.write('test content')-- subprocess.run(['git', '-C', temp_dir, 'add', 'test.txt'], check=True)-- # Create a test issue with problematic title- issue = Issue(- owner='test-owner',- repo='test-repo',- number=123,- title="Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>",- body='Test body',- labels=[],- assignees=[],- state='open',- created_at='2024-01-01T00:00:00Z',- updated_at='2024-01-01T00:00:00Z',- closed_at=None,- head_branch=None,- thread_ids=None,- )-- # Make the commit- make_commit(temp_dir, issue, 'issue')-- # Get the commit message- result = subprocess.run(- ['git', '-C', temp_dir, 'log', '-1', '--pretty=%B'],- capture_output=True,- text=True,- check=True,- )- commit_msg = result.stdout.strip()-- # The commit message should contain the quotes without excessive escaping- expected = "Fix issue #123: Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>"- assert commit_msg == expected, f'Expected: {expected}\nGot: {commit_msg}'---def test_pr_title_with_quotes(monkeypatch):- # Mock httpx.post to avoid actual API calls- class MockResponse:- def __init__(self, status_code=201):- self.status_code = status_code- self.text = ''-- def json(self):- return {'html_url': 'https://github.com/test/test/pull/1'}-- def raise_for_status(self):- pass-- def mock_post(*args, **kwargs):- # Verify that the PR title is not over-escaped- data = kwargs.get('json', {})- title = data.get('title', '')- expected = "Fix issue #123: Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>"- assert title == expected, (- f'PR title was incorrectly escaped.\nExpected: {expected}\nGot: {title}'- )- return MockResponse()-- class MockGetResponse:- def __init__(self, status_code=200):- self.status_code = status_code- self.text = ''-- def json(self):- return {'default_branch': 'main'}-- def raise_for_status(self):- pass-- monkeypatch.setattr('httpx.post', mock_post)- monkeypatch.setattr('httpx.get', lambda *args, **kwargs: MockGetResponse())- monkeypatch.setattr(- 'openhands.resolver.interfaces.github.GithubIssueHandler.branch_exists',- lambda *args, **kwargs: False,- )-- # Mock subprocess.run to avoid actual git commands- original_run = subprocess.run-- def mock_run(*args, **kwargs):- logger.info(f'Running command: {args[0] if args else kwargs.get("args", [])}')- if isinstance(args[0], list) and args[0][0] == 'git':- if 'push' in args[0]:- return subprocess.CompletedProcess(- args[0], returncode=0, stdout='', stderr=''- )- return original_run(*args, **kwargs)- return original_run(*args, **kwargs)-- monkeypatch.setattr('subprocess.run', mock_run)-- # Create a temporary directory and initialize git repo- with tempfile.TemporaryDirectory() as temp_dir:- logger.info('Initializing git repo...')- subprocess.run(['git', 'init', temp_dir], check=True)-- # Add these lines to configure git- subprocess.run(- ['git', '-C', temp_dir, 'config', 'user.name', 'Test User'], check=True- )- subprocess.run(- ['git', '-C', temp_dir, 'config', 'user.email', '[email protected]'],- check=True,- )-- # Create a test file and add it to git- test_file = os.path.join(temp_dir, 'test.txt')- with open(test_file, 'w') as f:- f.write('test content')-- logger.info('Adding and committing test file...')- subprocess.run(['git', '-C', temp_dir, 'add', 'test.txt'], check=True)- subprocess.run(- ['git', '-C', temp_dir, 'commit', '-m', 'Initial commit'], check=True- )-- # Create a test issue with problematic title- logger.info('Creating test issue...')- issue = Issue(- owner='test-owner',- repo='test-repo',- number=123,- title="Issue with 'quotes' and \"double quotes\" and <class 'ValueError'>",- body='Test body',- labels=[],- assignees=[],- state='open',- created_at='2024-01-01T00:00:00Z',- updated_at='2024-01-01T00:00:00Z',- closed_at=None,- head_branch=None,- thread_ids=None,- )-- # Try to send a PR - this will fail if the title is incorrectly escaped- logger.info('Sending PR...')-- send_pull_request(- issue=issue,- token='dummy-token',- username='test-user',- platform=ProviderType.GITHUB,- patch_dir=temp_dir,- pr_type='ready',- )diff --git a/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py b/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.pydeleted file mode 100644index 2cedb21b49..0000000000--- a/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py+++ /dev/null@@ -1,1000 +0,0 @@-import os-import tempfile-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openhands.core.config import LLMConfig-from openhands.events.action import CmdRunAction-from openhands.events.observation import (- CmdOutputMetadata,- CmdOutputObservation,- NullObservation,-)-from openhands.integrations.service_types import ProviderType-from openhands.llm.llm import LLM-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandler-from openhands.resolver.interfaces.issue import Issue, ReviewThread-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)-from openhands.resolver.issue_resolver import (- IssueResolver,-)-from openhands.resolver.resolver_output import ResolverOutput---def default_mock_args():- """Fixture that provides a default mock args object with common values.-- Tests can override specific attributes as needed.- """- mock_args = MagicMock()- mock_args.selected_repo = 'test-owner/test-repo'- mock_args.token = 'test-token'- mock_args.username = 'test-user'- mock_args.max_iterations = 5- mock_args.output_dir = '/tmp'- mock_args.llm_model = 'test'- mock_args.llm_api_key = 'test'- mock_args.llm_base_url = None- mock_args.base_domain = None- mock_args.runtime_container_image = None- mock_args.is_experimental = False- mock_args.issue_number = None- mock_args.comment_id = None- mock_args.repo_instruction_file = None- mock_args.issue_type = 'issue'- mock_args.prompt_file = None- return mock_args---def mock_gitlab_token():- """Fixture that patches the identify_token function to return GitLab provider type.-- This eliminates the need for repeated patching in each test function.- """- with patch(- 'openhands.resolver.issue_resolver.identify_token',- return_value=ProviderType.GITLAB,- ) as patched:- yield patched---def mock_output_dir():- with tempfile.TemporaryDirectory() as temp_dir:- repo_path = os.path.join(temp_dir, 'repo')- # Initialize a Gitlab repo in "repo" and add a commit with "README.md"- os.makedirs(repo_path)- os.system(f'git init {repo_path}')- readme_path = os.path.join(repo_path, 'README.md')- with open(readme_path, 'w') as f:- f.write('hello world')- os.system(f'git -C {repo_path} add README.md')- os.system(f"git -C {repo_path} commit -m 'Initial commit'")- yield temp_dir---def mock_subprocess():- with patch('subprocess.check_output') as mock_check_output:- yield mock_check_output---def mock_os():- with patch('os.system') as mock_system, patch('os.path.join') as mock_join:- yield mock_system, mock_join---def mock_user_instructions_template():- return 'Issue: {{ body }}\n\nPlease fix this issue.'---def mock_conversation_instructions_template():- return 'Instructions: {{ repo_instruction }}'---def mock_followup_prompt_template():- return 'Issue context: {{ issues }}\n\nReview comments: {{ review_comments }}\n\nReview threads: {{ review_threads }}\n\nFiles: {{ files }}\n\nThread comments: {{ thread_context }}\n\nPlease fix this issue.'---def create_cmd_output(exit_code: int, content: str, command: str):- return CmdOutputObservation(- content=content,- command=command,- metadata=CmdOutputMetadata(exit_code=exit_code),- )---def test_initialize_runtime(default_mock_args, mock_gitlab_token):- mock_runtime = MagicMock()-- if os.getenv('GITLAB_CI') == 'true':- mock_runtime.run_action.side_effect = [- create_cmd_output(exit_code=0, content='', command='cd /workspace'),- create_cmd_output(- exit_code=0, content='', command='sudo chown -R 1001:0 /workspace/*'- ),- create_cmd_output(- exit_code=0, content='', command='git config --global core.pager ""'- ),- ]- else:- mock_runtime.run_action.side_effect = [- create_cmd_output(exit_code=0, content='', command='cd /workspace'),- create_cmd_output(- exit_code=0, content='', command='git config --global core.pager ""'- ),- ]-- # Create resolver with mocked token identification- resolver = IssueResolver(default_mock_args)-- resolver.initialize_runtime(mock_runtime)-- if os.getenv('GITLAB_CI') == 'true':- assert mock_runtime.run_action.call_count == 3- else:- assert mock_runtime.run_action.call_count == 2-- mock_runtime.run_action.assert_any_call(CmdRunAction(command='cd /workspace'))- if os.getenv('GITLAB_CI') == 'true':- mock_runtime.run_action.assert_any_call(- CmdRunAction(command='sudo chown -R 1001:0 /workspace/*')- )- mock_runtime.run_action.assert_any_call(- CmdRunAction(command='git config --global core.pager ""')- )---async def test_resolve_issue_no_issues_found(default_mock_args, mock_gitlab_token):- """Test the resolve_issue method when no issues are found."""- # Mock dependencies- mock_handler = MagicMock()- mock_handler.get_converted_issues.return_value = [] # Return empty list-- # Customize the mock args for this test- default_mock_args.issue_number = 5432-- # Create a resolver instance with mocked token identification- resolver = IssueResolver(default_mock_args)-- # Mock the issue handler- resolver.issue_handler = mock_handler-- # Test that the correct exception is raised- with pytest.raises(ValueError) as exc_info:- await resolver.resolve_issue()-- # Verify the error message- assert 'No issues found for issue number 5432' in str(exc_info.value)- assert 'test-owner/test-repo' in str(exc_info.value)-- mock_handler.get_converted_issues.assert_called_once_with(- issue_numbers=[5432], comment_id=None- )---def test_download_issues_from_gitlab():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), llm_config- )-- mock_issues_response = MagicMock()- mock_issues_response.json.side_effect = [- [- {'iid': 1, 'title': 'Issue 1', 'description': 'This is an issue'},- {- 'iid': 2,- 'title': 'PR 1',- 'description': 'This is a pull request',- 'pull_request': {},- },- {'iid': 3, 'title': 'Issue 2', 'description': 'This is another issue'},- ],- None,- ]- mock_issues_response.raise_for_status = MagicMock()-- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = []- mock_comments_response.raise_for_status = MagicMock()-- def get_mock_response(url, *args, **kwargs):- if '/notes' in url:- return mock_comments_response- return mock_issues_response-- with patch('httpx.get', side_effect=get_mock_response):- issues = handler.get_converted_issues(issue_numbers=[1, 3])-- assert len(issues) == 2- assert handler.issue_type == 'issue'- assert all(isinstance(issue, Issue) for issue in issues)- assert [issue.number for issue in issues] == [1, 3]- assert [issue.title for issue in issues] == ['Issue 1', 'Issue 2']- assert [issue.review_comments for issue in issues] == [None, None]- assert [issue.closing_issues for issue in issues] == [None, None]- assert [issue.thread_ids for issue in issues] == [None, None]---def test_download_pr_from_gitlab():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextPR(GitlabPRHandler('owner', 'repo', 'token'), llm_config)- mock_pr_response = MagicMock()- mock_pr_response.json.side_effect = [- [- {- 'iid': 1,- 'title': 'PR 1',- 'description': 'This is a pull request',- 'source_branch': 'b1',- },- {- 'iid': 2,- 'title': 'My PR',- 'description': 'This is another pull request',- 'source_branch': 'b2',- },- {- 'iid': 3,- 'title': 'PR 3',- 'description': 'Final PR',- 'source_branch': 'b3',- },- ],- None,- ]- mock_pr_response.raise_for_status = MagicMock()-- # Mock for related issues response- mock_related_issuse_response = MagicMock()- mock_related_issuse_response.json.return_value = [- {'description': 'Issue 1 body', 'iid': 1},- {'description': 'Issue 2 body', 'iid': 2},- ]- mock_related_issuse_response.raise_for_status = MagicMock()-- # Mock for PR comments response- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [] # No PR comments- mock_comments_response.raise_for_status = MagicMock()-- # Mock for GraphQL request (for download_pr_metadata)- mock_graphql_response = MagicMock()- mock_graphql_response.json.side_effect = lambda: {- 'data': {- 'project': {- 'mergeRequest': {- 'discussions': {- 'edges': [- {- 'node': {- 'id': '1',- 'resolved': False,- 'resolvable': True,- 'notes': {- 'nodes': [- {- 'body': 'Unresolved comment 1',- 'position': {- 'filePath': '/frontend/header.tsx',- },- },- {- 'body': 'Follow up thread',- },- ]- },- }- },- {- 'node': {- 'id': '2',- 'resolved': True,- 'resolvable': True,- 'notes': {- 'nodes': [- {- 'body': 'Resolved comment 1',- 'position': {- 'filePath': '/some/file.py',- },- },- ]- },- }- },- {- 'node': {- 'id': '3',- 'resolved': False,- 'resolvable': True,- 'notes': {- 'nodes': [- {- 'body': 'Unresolved comment 3',- 'position': {- 'filePath': '/another/file.py',- },- },- ]- },- }- },- ]- },- }- }- }- }-- mock_graphql_response.raise_for_status = MagicMock()-- def get_mock_response(url, *args, **kwargs):- if '/notes' in url:- return mock_comments_response- if '/related_issues' in url:- return mock_related_issuse_response- return mock_pr_response-- with patch('httpx.get', side_effect=get_mock_response):- with patch('httpx.post', return_value=mock_graphql_response):- issues = handler.get_converted_issues(issue_numbers=[1, 2, 3])-- assert len(issues) == 3- assert handler.issue_type == 'pr'- assert all(isinstance(issue, Issue) for issue in issues)- assert [issue.number for issue in issues] == [1, 2, 3]- assert [issue.title for issue in issues] == ['PR 1', 'My PR', 'PR 3']- assert [issue.head_branch for issue in issues] == ['b1', 'b2', 'b3']-- assert len(issues[0].review_threads) == 2 # Only unresolved threads- assert (- issues[0].review_threads[0].comment- == 'Unresolved comment 1\n---\nlatest feedback:\nFollow up thread\n'- )- assert issues[0].review_threads[0].files == ['/frontend/header.tsx']- assert (- issues[0].review_threads[1].comment- == 'latest feedback:\nUnresolved comment 3\n'- )- assert issues[0].review_threads[1].files == ['/another/file.py']- assert issues[0].closing_issues == ['Issue 1 body', 'Issue 2 body']- assert issues[0].thread_ids == ['1', '3']---async def test_complete_runtime(default_mock_args, mock_gitlab_token):- mock_runtime = MagicMock()- mock_runtime.run_action.side_effect = [- create_cmd_output(exit_code=0, content='', command='cd /workspace'),- create_cmd_output(- exit_code=0, content='', command='git config --global core.pager ""'- ),- create_cmd_output(- exit_code=0,- content='',- command='git config --global --add safe.directory /workspace',- ),- create_cmd_output(exit_code=0, content='', command='git add -A'),- create_cmd_output(- exit_code=0,- content='git diff content',- command='git diff --no-color --cached base_commit_hash',- ),- ]-- # Create a resolver instance with mocked token identification- resolver = IssueResolver(default_mock_args)-- result = await resolver.complete_runtime(mock_runtime, 'base_commit_hash')-- assert result == {'git_patch': 'git diff content'}- assert mock_runtime.run_action.call_count == 5--- 'test_case',- [- {- 'name': 'successful_run',- 'run_controller_return': MagicMock(- history=[NullObservation(content='')],- metrics=MagicMock(- get=MagicMock(return_value={'test_result': 'passed'})- ),- last_error=None,- ),- 'run_controller_raises': None,- 'expected_success': True,- 'expected_error': None,- 'expected_explanation': 'Issue resolved successfully',- 'is_pr': False,- 'comment_success': None,- },- {- 'name': 'value_error',- 'run_controller_raises': ValueError('Test value error'),- 'expected_success': False,- 'expected_error': 'Agent failed to run or crashed',- 'expected_explanation': 'Agent failed to run',- 'is_pr': False,- 'comment_success': None,- },- {- 'name': 'runtime_error',- 'run_controller_raises': RuntimeError('Test runtime error'),- 'expected_success': False,- 'expected_error': 'Agent failed to run or crashed',- 'expected_explanation': 'Agent failed to run',- 'is_pr': False,- 'comment_success': None,- },- {- 'name': 'json_decode_error',- 'run_controller_return': MagicMock(- history=[NullObservation(content='')],- metrics=MagicMock(- get=MagicMock(return_value={'test_result': 'passed'})- ),- last_error=None,- ),- 'run_controller_raises': None,- 'expected_success': True,- 'expected_error': None,- 'expected_explanation': 'Non-JSON explanation',- 'is_pr': True,- 'comment_success': [True, False],- },- ],-)-async def test_process_issue(- default_mock_args,- mock_gitlab_token,- mock_output_dir,- mock_user_instructions_template,- test_case,-):- """Test the process_issue method with different scenarios."""- # Set up test data- issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- base_commit = 'abcdef1234567890'-- # Customize the mock args for this test- default_mock_args.output_dir = mock_output_dir- default_mock_args.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'-- # Create a resolver instance with mocked token identification- resolver = IssueResolver(default_mock_args)- resolver.user_instructions_prompt_template = mock_user_instructions_template-- # Mock the handler with LLM config- llm_config = LLMConfig(model='test', api_key='test')- handler_instance = MagicMock()- handler_instance.guess_success.return_value = (- test_case['expected_success'],- test_case.get('comment_success', None),- test_case['expected_explanation'],- )- handler_instance.get_instruction.return_value = (- 'Test instruction',- 'Test conversation instructions',- [],- )- handler_instance.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'- handler_instance.llm = LLM(llm_config, service_id='test-service')-- # Create mock runtime and mock run_controller- mock_runtime = MagicMock()- mock_runtime.connect = AsyncMock()- mock_create_runtime = MagicMock(return_value=mock_runtime)-- # Configure run_controller mock based on test case- mock_run_controller = AsyncMock()- if test_case.get('run_controller_raises'):- mock_run_controller.side_effect = test_case['run_controller_raises']- else:- mock_run_controller.return_value = test_case['run_controller_return']-- # Patch the necessary functions and methods- with (- patch('openhands.resolver.issue_resolver.create_runtime', mock_create_runtime),- patch('openhands.resolver.issue_resolver.run_controller', mock_run_controller),- patch.object(- resolver, 'complete_runtime', return_value={'git_patch': 'test patch'}- ),- patch.object(resolver, 'initialize_runtime') as mock_initialize_runtime,- patch(- 'openhands.resolver.issue_resolver.SandboxConfig', return_value=MagicMock()- ),- patch(- 'openhands.resolver.issue_resolver.OpenHandsConfig',- return_value=MagicMock(),- ),- ):- # Call the process_issue method- result = await resolver.process_issue(issue, base_commit, handler_instance)-- mock_create_runtime.assert_called_once()- mock_runtime.connect.assert_called_once()- mock_initialize_runtime.assert_called_once()- mock_run_controller.assert_called_once()- resolver.complete_runtime.assert_awaited_once_with(mock_runtime, base_commit)-- # Assert the result matches our expectations- assert isinstance(result, ResolverOutput)- assert result.issue == issue- assert result.base_commit == base_commit- assert result.git_patch == 'test patch'- assert result.success == test_case['expected_success']- assert result.result_explanation == test_case['expected_explanation']- assert result.error == test_case['expected_error']-- if test_case['expected_success']:- handler_instance.guess_success.assert_called_once()- else:- handler_instance.guess_success.assert_not_called()---def test_get_instruction(- mock_user_instructions_template,- mock_conversation_instructions_template,- mock_followup_prompt_template,-):- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue refer to image ',- )- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, images_urls = issue_handler.get_instruction(- issue,- mock_user_instructions_template,- mock_conversation_instructions_template,- None,- )- expected_instruction = 'Issue: Test Issue\n\nThis is a test issue refer to image \n\nPlease fix this issue.'-- assert images_urls == ['https://sampleimage.com/image1.png']- assert issue_handler.issue_type == 'issue'- assert instruction == expected_instruction- assert conversation_instructions is not None-- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue',- closing_issues=['Issue 1 fix the type'],- review_threads=[- ReviewThread(- comment="There is still a typo 'pthon' instead of 'python'", files=[]- )- ],- thread_comments=[- "I've left review comments, please address them",- 'This is a valid concern.',- ],- )-- pr_handler = ServiceContextPR(- GitlabPRHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, images_urls = pr_handler.get_instruction(- issue,- mock_followup_prompt_template,- mock_conversation_instructions_template,- None,- )- expected_instruction = "Issue context: [\n \"Issue 1 fix the type\"\n]\n\nReview comments: None\n\nReview threads: [\n \"There is still a typo 'pthon' instead of 'python'\"\n]\n\nFiles: []\n\nThread comments: I've left review comments, please address them\n---\nThis is a valid concern.\n\nPlease fix this issue."-- assert images_urls == []- assert pr_handler.issue_type == 'pr'- # Compare content ignoring exact formatting- assert "There is still a typo 'pthon' instead of 'python'" in instruction- assert "I've left review comments, please address them" in instruction- assert 'This is a valid concern' in instruction- assert conversation_instructions is not None---def test_file_instruction():- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue ',- )- # load prompt from openhands/resolver/prompts/resolve/basic.jinja- with open('openhands/resolver/prompts/resolve/basic.jinja', 'r') as f:- prompt = f.read()-- with open(- 'openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja', 'r'- ) as f:- conversation_instructions_template = f.read()-- # Test without thread comments- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, images_urls = issue_handler.get_instruction(- issue, prompt, conversation_instructions_template, None- )- expected_instruction = """Please fix the following issue for the repository in /workspace.-An environment has been set up for you to start working. You may assume all necessary tools are installed.--# Problem Statement-Test Issue--This is a test issue """-- expected_conversation_instructions = """IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.-You SHOULD INCLUDE PROPER INDENTATION in your edit commands.--When you think you have fixed the issue through code changes, please finish the interaction."""-- assert instruction == expected_instruction- assert conversation_instructions == expected_conversation_instructions- assert images_urls == ['https://sampleimage.com/sample.png']---def test_file_instruction_with_repo_instruction():- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue',- )- # load prompt from openhands/resolver/prompts/resolve/basic.jinja- with open('openhands/resolver/prompts/resolve/basic.jinja', 'r') as f:- prompt = f.read()-- with open(- 'openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja', 'r'- ) as f:- conversation_instructions_prompt = f.read()-- # load repo instruction from openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands-resolver.txt- with open(- 'openhands/resolver/prompts/repo_instructions/all-hands-ai___openhands-resolver.txt',- 'r',- ) as f:- repo_instruction = f.read()-- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )- instruction, conversation_instructions, image_urls = issue_handler.get_instruction(- issue, prompt, conversation_instructions_prompt, repo_instruction- )-- expected_instruction = """Please fix the following issue for the repository in /workspace.-An environment has been set up for you to start working. You may assume all necessary tools are installed.--# Problem Statement-Test Issue--This is a test issue"""-- expected_conversation_instructions = """IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.-You SHOULD INCLUDE PROPER INDENTATION in your edit commands.--Some basic information about this repository:-This is a Python repo for openhands-resolver, a library that attempts to resolve github issues with the AI agent OpenHands.--- Setup: `poetry install --with test --with dev`-- Testing: `poetry run pytest tests/test_*.py`---When you think you have fixed the issue through code changes, please finish the interaction."""-- assert instruction == expected_instruction- assert conversation_instructions == expected_conversation_instructions- assert conversation_instructions is not None- assert issue_handler.issue_type == 'issue'- assert image_urls == []---def test_guess_success():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- mock_history = [create_cmd_output(exit_code=0, content='', command='cd /workspace')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\ntrue\n--- explanation\nIssue resolved successfully'- )- )- ]- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert success- assert explanation == 'Issue resolved successfully'---def test_guess_success_with_thread_comments():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- thread_comments=[- 'First comment',- 'Second comment',- 'latest feedback:\nPlease add tests',- ],- )- mock_history = [MagicMock(message='I have added tests for this case')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\ntrue\n--- explanation\nTests have been added to verify thread comments handling'- )- )- ]- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert success- assert 'Tests have been added' in explanation---def test_instruction_with_thread_comments():- # Create an issue with thread comments- issue = Issue(- owner='test_owner',- repo='test_repo',- number=123,- title='Test Issue',- body='This is a test issue',- thread_comments=[- 'First comment',- 'Second comment',- 'latest feedback:\nPlease add tests',- ],- )-- # Load the basic prompt template- with open('openhands/resolver/prompts/resolve/basic.jinja', 'r') as f:- prompt = f.read()-- with open(- 'openhands/resolver/prompts/resolve/basic-conversation-instructions.jinja', 'r'- ) as f:- conversation_instructions_template = f.read()-- llm_config = LLMConfig(model='test', api_key='test')- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), llm_config- )- instruction, conversation_instructions, images_urls = issue_handler.get_instruction(- issue, prompt, conversation_instructions_template, None- )-- # Verify that thread comments are included in the instruction- assert 'First comment' in instruction- assert 'Second comment' in instruction- assert 'Please add tests' in instruction- assert 'Issue Thread Comments:' in instruction- assert images_urls == []---def test_guess_success_failure():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- thread_comments=[- 'First comment',- 'Second comment',- 'latest feedback:\nPlease add tests',- ],- )- mock_history = [MagicMock(message='I have added tests for this case')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\ntrue\n--- explanation\nTests have been added to verify thread comments handling'- )- )- ]- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert success- assert 'Tests have been added' in explanation---def test_guess_success_negative_case():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- mock_history = [create_cmd_output(exit_code=0, content='', command='cd /workspace')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(- message=MagicMock(- content='--- success\nfalse\n--- explanation\nIssue not resolved'- )- )- ]- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert not success- assert explanation == 'Issue not resolved'---def test_guess_success_invalid_output():- mock_issue = Issue(- owner='test_owner',- repo='test_repo',- number=1,- title='Test Issue',- body='This is a test issue',- )- mock_history = [create_cmd_output(exit_code=0, content='', command='cd /workspace')]- mock_llm_config = LLMConfig(model='test_model', api_key='test_api_key')-- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(message=MagicMock(content='This is not a valid output'))- ]- issue_handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), mock_llm_config- )-- with patch.object(- LLM, 'completion', MagicMock(return_value=mock_completion_response)- ):- success, comment_success, explanation = issue_handler.guess_success(- mock_issue, mock_history- )- assert issue_handler.issue_type == 'issue'- assert comment_success is None- assert not success- assert (- explanation- == 'Failed to decode answer from LLM response: This is not a valid output'- )---def test_download_issue_with_specific_comment():- llm_config = LLMConfig(model='test', api_key='test')- handler = ServiceContextIssue(- GitlabIssueHandler('owner', 'repo', 'token'), llm_config- )-- # Define the specific comment_id to filter- specific_comment_id = 101-- # Mock issue and comment responses- mock_issue_response = MagicMock()- mock_issue_response.json.side_effect = [- [- {'iid': 1, 'title': 'Issue 1', 'description': 'This is an issue'},- ],- None,- ]- mock_issue_response.raise_for_status = MagicMock()-- mock_comments_response = MagicMock()- mock_comments_response.json.return_value = [- {- 'id': specific_comment_id,- 'body': 'Specific comment body',- },- {- 'id': 102,- 'body': 'Another comment body',- },- ]- mock_comments_response.raise_for_status = MagicMock()-- def get_mock_response(url, *args, **kwargs):- if '/notes' in url:- return mock_comments_response-- return mock_issue_response-- with patch('httpx.get', side_effect=get_mock_response):- issues = handler.get_converted_issues(- issue_numbers=[1], comment_id=specific_comment_id- )-- assert len(issues) == 1- assert issues[0].number == 1- assert issues[0].title == 'Issue 1'- assert issues[0].thread_comments == ['Specific comment body']---if __name__ == '__main__':- pytest.main()diff --git a/tests/unit/resolver/gitlab/test_gitlab_send_pull_request.py b/tests/unit/resolver/gitlab/test_gitlab_send_pull_request.pydeleted file mode 100644index d342273fbe..0000000000--- a/tests/unit/resolver/gitlab/test_gitlab_send_pull_request.py+++ /dev/null@@ -1,1235 +0,0 @@-import os-import tempfile-from unittest.mock import ANY, MagicMock, call, patch-from urllib.parse import quote--import pytest--from openhands.core.config import LLMConfig-from openhands.integrations.service_types import ProviderType-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler-from openhands.resolver.interfaces.issue import ReviewThread-from openhands.resolver.resolver_output import Issue, ResolverOutput-from openhands.resolver.send_pull_request import (- apply_patch,- initialize_repo,- load_single_resolver_output,- main,- make_commit,- process_single_issue,- send_pull_request,- update_existing_pull_request,-)---def mock_output_dir():- with tempfile.TemporaryDirectory() as temp_dir:- repo_path = os.path.join(temp_dir, 'repo')- # Initialize a Gitlab repo in "repo" and add a commit with "README.md"- os.makedirs(repo_path)- os.system(f'git init {repo_path}')- readme_path = os.path.join(repo_path, 'README.md')- with open(readme_path, 'w') as f:- f.write('hello world')- os.system(f'git -C {repo_path} add README.md')- os.system(f"git -C {repo_path} commit -m 'Initial commit'")- yield temp_dir---def mock_issue():- return Issue(- number=42,- title='Test Issue',- owner='test-owner',- repo='test-repo',- body='Test body',- )---def mock_llm_config():- return LLMConfig()---def test_load_single_resolver_output():- mock_output_jsonl = 'tests/unit/resolver/mock_output/output.jsonl'-- # Test loading an existing issue- resolver_output = load_single_resolver_output(mock_output_jsonl, 5)- assert isinstance(resolver_output, ResolverOutput)- assert resolver_output.issue.number == 5- assert resolver_output.issue.title == 'Add MIT license'- assert resolver_output.issue.owner == 'neubig'- assert resolver_output.issue.repo == 'pr-viewer'-- # Test loading a non-existent issue- with pytest.raises(ValueError):- load_single_resolver_output(mock_output_jsonl, 999)---def test_apply_patch(mock_output_dir):- # Create a sample file in the mock repo- sample_file = os.path.join(mock_output_dir, 'sample.txt')- with open(sample_file, 'w') as f:- f.write('Original content')-- # Create a sample patch- patch_content = """-diff --git a/sample.txt b/sample.txt-index 9daeafb..b02def2 100644---- a/sample.txt-+++ b/sample.txt-@@ -1 +1,2 @@--Original content-+Updated content-+New line-"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the file was updated correctly- with open(sample_file, 'r') as f:- updated_content = f.read()-- assert updated_content.strip() == 'Updated content\nNew line'.strip()---def test_apply_patch_preserves_line_endings(mock_output_dir):- # Create sample files with different line endings- unix_file = os.path.join(mock_output_dir, 'unix_style.txt')- dos_file = os.path.join(mock_output_dir, 'dos_style.txt')-- with open(unix_file, 'w', newline='\n') as f:- f.write('Line 1\nLine 2\nLine 3')-- with open(dos_file, 'w', newline='\r\n') as f:- f.write('Line 1\r\nLine 2\r\nLine 3')-- # Create patches for both files- unix_patch = """-diff --git a/unix_style.txt b/unix_style.txt-index 9daeafb..b02def2 100644---- a/unix_style.txt-+++ b/unix_style.txt-@@ -1,3 +1,3 @@- Line 1--Line 2-+Updated Line 2- Line 3-"""-- dos_patch = """-diff --git a/dos_style.txt b/dos_style.txt-index 9daeafb..b02def2 100644---- a/dos_style.txt-+++ b/dos_style.txt-@@ -1,3 +1,3 @@- Line 1--Line 2-+Updated Line 2- Line 3-"""-- # Apply patches- apply_patch(mock_output_dir, unix_patch)- apply_patch(mock_output_dir, dos_patch)-- # Check if line endings are preserved- with open(unix_file, 'rb') as f:- unix_content = f.read()- with open(dos_file, 'rb') as f:- dos_content = f.read()-- assert b'\r\n' not in unix_content, (- 'Unix-style line endings were changed to DOS-style'- )- assert b'\r\n' in dos_content, 'DOS-style line endings were changed to Unix-style'-- # Check if content was updated correctly- assert unix_content.decode('utf-8').split('\n')[1] == 'Updated Line 2'- assert dos_content.decode('utf-8').split('\r\n')[1] == 'Updated Line 2'---def test_apply_patch_create_new_file(mock_output_dir):- # Create a patch that adds a new file- patch_content = """-diff --git a/new_file.txt b/new_file.txt-new file mode 100644-index 0000000..3b18e51---- /dev/null-+++ b/new_file.txt-@@ -0,0 +1 @@-+hello world-"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the new file was created- new_file_path = os.path.join(mock_output_dir, 'new_file.txt')- assert os.path.exists(new_file_path), 'New file was not created'-- # Check if the file content is correct- with open(new_file_path, 'r') as f:- content = f.read().strip()- assert content == 'hello world', 'File content is incorrect'---def test_apply_patch_rename_file(mock_output_dir):- # Create a sample file in the mock repo- old_file = os.path.join(mock_output_dir, 'old_name.txt')- with open(old_file, 'w') as f:- f.write('This file will be renamed')-- # Create a patch that renames the file- patch_content = """diff --git a/old_name.txt b/new_name.txt-similarity index 100%-rename from old_name.txt-rename to new_name.txt"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the file was renamed- new_file = os.path.join(mock_output_dir, 'new_name.txt')- assert not os.path.exists(old_file), 'Old file still exists'- assert os.path.exists(new_file), 'New file was not created'-- # Check if the content is preserved- with open(new_file, 'r') as f:- content = f.read()- assert content == 'This file will be renamed'---def test_apply_patch_delete_file(mock_output_dir):- # Create a sample file in the mock repo- sample_file = os.path.join(mock_output_dir, 'to_be_deleted.txt')- with open(sample_file, 'w') as f:- f.write('This file will be deleted')-- # Create a patch that deletes the file- patch_content = """-diff --git a/to_be_deleted.txt b/to_be_deleted.txt-deleted file mode 100644-index 9daeafb..0000000---- a/to_be_deleted.txt-+++ /dev/null-@@ -1 +0,0 @@--This file will be deleted-"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if the file was deleted- assert not os.path.exists(sample_file), 'File was not deleted'---def test_initialize_repo(mock_output_dir):- issue_type = 'issue'- # Copy the repo to patches- ISSUE_NUMBER = 3- initialize_repo(mock_output_dir, ISSUE_NUMBER, issue_type)- patches_dir = os.path.join(mock_output_dir, 'patches', f'issue_{ISSUE_NUMBER}')-- # Check if files were copied correctly- assert os.path.exists(os.path.join(patches_dir, 'README.md'))-- # Check file contents- with open(os.path.join(patches_dir, 'README.md'), 'r') as f:- assert f.read() == 'hello world'---@patch('openhands.resolver.interfaces.gitlab.GitlabIssueHandler.reply_to_comment')-@patch('httpx.post')-@patch('subprocess.run')-@patch('openhands.resolver.send_pull_request.LLM')-def test_update_existing_pull_request(- mock_llm_class,- mock_subprocess_run,- mock_requests_post,- mock_reply_to_comment,-):- # Arrange: Set up test data- issue = Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Test PR',- body='This is a test PR',- thread_ids=['comment1', 'comment2'],- head_branch='test-branch',- )- token = 'test-token'- username = 'test-user'- patch_dir = '/path/to/patch'- additional_message = '["Fixed bug in function A", "Updated documentation for B"]'-- # Mock the subprocess.run call for git push- mock_subprocess_run.return_value = MagicMock(returncode=0)-- # Mock the requests.post call for adding a PR comment- mock_requests_post.return_value.status_code = 201-- # Mock LLM instance and completion call- mock_llm_instance = MagicMock()- mock_completion_response = MagicMock()- mock_completion_response.choices = [- MagicMock(message=MagicMock(content='This is an issue resolution.'))- ]- mock_llm_instance.completion.return_value = mock_completion_response- mock_llm_class.return_value = mock_llm_instance-- llm_config = LLMConfig()-- # Act: Call the function without comment_message to test auto-generation- result = update_existing_pull_request(- issue,- token,- username,- ProviderType.GITLAB,- patch_dir,- llm_config,- comment_message=None,- additional_message=additional_message,- )-- # Assert: Check if the git push command was executed- push_command = (- f'git -C {patch_dir} push '- f'https://{username}:{token}@gitlab.com/'- f'{issue.owner}/{issue.repo}.git {issue.head_branch}'- )- mock_subprocess_run.assert_called_once_with(- push_command, shell=True, capture_output=True, text=True- )-- # Assert: Check if the auto-generated comment was posted to the PR- comment_url = f'https://gitlab.com/api/v4/projects/{quote(f"{issue.owner}/{issue.repo}", safe="")}/issues/{issue.number}/notes'- expected_comment = 'This is an issue resolution.'- mock_requests_post.assert_called_once_with(- comment_url,- headers={- 'Authorization': f'Bearer {token}',- 'Accept': 'application/json',- },- json={'body': expected_comment},- )-- # Assert: Check if the reply_to_comment function was called for each thread ID- mock_reply_to_comment.assert_has_calls(- [- call(issue.number, 'comment1', 'Fixed bug in function A'),- call(issue.number, 'comment2', 'Updated documentation for B'),- ]- )-- # Assert: Check the returned PR URL- assert (- result- == f'https://gitlab.com/{issue.owner}/{issue.repo}/-/merge_requests/{issue.number}'- )--- 'pr_type,target_branch,pr_title',- [- ('branch', None, None),- ('draft', None, None),- ('ready', None, None),- ('branch', 'feature', None),- ('draft', 'develop', None),- ('ready', 'staging', None),- ('ready', None, 'Custom PR Title'),- ('draft', 'develop', 'Another Custom Title'),- ],-)-@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request(- mock_get,- mock_post,- mock_run,- mock_issue,- mock_llm_config,- mock_output_dir,- pr_type,- target_branch,- pr_title,-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses based on whether target_branch is specified- if target_branch:- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(status_code=200), # Target branch exists- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- ]- else:- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- ]-- mock_post.return_value.json.return_value = {- 'web_url': 'https://gitlab.com/test-owner/test-repo/-/merge_requests/1',- }-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function- result = send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITLAB,- patch_dir=repo_path,- pr_type=pr_type,- target_branch=target_branch,- pr_title=pr_title,- )-- # Assert API calls- expected_get_calls = 2- if pr_type == 'branch':- expected_get_calls = 3-- assert mock_get.call_count == expected_get_calls-- # Check branch creation and push- assert mock_run.call_count == 2- checkout_call, push_call = mock_run.call_args_list-- assert checkout_call == call(- ['git', '-C', repo_path, 'checkout', '-b', 'openhands-fix-issue-42'],- capture_output=True,- text=True,- )- assert push_call == call(- [- 'git',- '-C',- repo_path,- 'push',- 'https://test-user:[email protected]/test-owner/test-repo.git',- 'openhands-fix-issue-42',- ],- capture_output=True,- text=True,- )-- # Check PR creation based on pr_type- if pr_type == 'branch':- assert (- result- == 'https://gitlab.com/test-owner/test-repo/-/compare/main...openhands-fix-issue-42'- )- mock_post.assert_not_called()- else:- assert result == 'https://gitlab.com/test-owner/test-repo/-/merge_requests/1'- mock_post.assert_called_once()- post_data = mock_post.call_args[1]['json']- expected_title = pr_title if pr_title else 'Fix issue #42: Test Issue'- assert post_data['title'] == expected_title- assert post_data['description'].startswith('This pull request fixes #42.')- assert post_data['source_branch'] == 'openhands-fix-issue-42'- assert post_data['target_branch'] == (- target_branch if target_branch else 'main'- )- assert post_data['draft'] == (pr_type == 'draft')---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.put')-@patch('httpx.get')-def test_send_pull_request_with_reviewer(- mock_get,- mock_put,- mock_post,- mock_run,- mock_issue,- mock_output_dir,- mock_llm_config,-):- repo_path = os.path.join(mock_output_dir, 'repo')- reviewer = 'test-reviewer'-- # Mock API responses- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- MagicMock(json=lambda: [{'id': 123}]), # Get user data- ]-- # Mock PR creation response- mock_post.side_effect = [- MagicMock(- status_code=200,- json=lambda: {- 'web_url': 'https://gitlab.com/test-owner/test-repo/-/merge_requests/1',- 'iid': 1,- },- ), # PR creation- ]-- # Mock request reviewers response- mock_put.side_effect = [- MagicMock(status_code=200), # Reviewer request- ]-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function with reviewer- result = send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITLAB,- patch_dir=repo_path,- pr_type='ready',- reviewer=reviewer,- )-- # Assert API calls- assert mock_get.call_count == 3- assert mock_post.call_count == 1- assert mock_put.call_count == 1-- # Check PR creation- pr_create_call = mock_post.call_args_list[0]- assert pr_create_call[1]['json']['title'] == 'Fix issue #42: Test Issue'-- # Check reviewer request- reviewer_request_call = mock_put.call_args_list[0]- assert (- reviewer_request_call[0][0]- == 'https://gitlab.com/api/v4/projects/test-owner%2Ftest-repo/merge_requests/1'- )- assert reviewer_request_call[1]['json'] == {'reviewer_ids': [123]}-- # Check the result URL- assert result == 'https://gitlab.com/test-owner/test-repo/-/merge_requests/1'---@patch('httpx.get')-def test_send_pull_request_invalid_target_branch(- mock_get, mock_issue, mock_output_dir, mock_llm_config-):- """Test that an error is raised when specifying a non-existent target branch"""- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API response for non-existent branch- mock_get.side_effect = [- MagicMock(status_code=404), # Branch doesn't exist- MagicMock(status_code=404), # Target branch doesn't exist- ]-- # Test that ValueError is raised when target branch doesn't exist- with pytest.raises(- ValueError, match='Target branch nonexistent-branch does not exist'- ):- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITLAB,- patch_dir=repo_path,- pr_type='ready',- target_branch='nonexistent-branch',- )-- # Verify API calls- assert mock_get.call_count == 2---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request_git_push_failure(- mock_get, mock_post, mock_run, mock_issue, mock_output_dir, mock_llm_config-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses- mock_get.return_value = MagicMock(json=lambda: {'default_branch': 'main'})-- # Mock the subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=1, stderr='Error: failed to push some refs'), # git push- ]-- # Test that RuntimeError is raised when git push fails- with pytest.raises(- RuntimeError, match='Failed to push changes to the remote repository'- ):- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITLAB,- patch_dir=repo_path,- pr_type='ready',- )-- # Assert that subprocess.run was called twice- assert mock_run.call_count == 2-- # Check the git checkout -b command- checkout_call = mock_run.call_args_list[0]- assert checkout_call[0][0] == [- 'git',- '-C',- repo_path,- 'checkout',- '-b',- 'openhands-fix-issue-42',- ]-- # Check the git push command- push_call = mock_run.call_args_list[1]- assert push_call[0][0] == [- 'git',- '-C',- repo_path,- 'push',- 'https://test-user:[email protected]/test-owner/test-repo.git',- 'openhands-fix-issue-42',- ]-- # Assert that no pull request was created- mock_post.assert_not_called()---@patch('subprocess.run')-@patch('httpx.post')-@patch('httpx.get')-def test_send_pull_request_permission_error(- mock_get, mock_post, mock_run, mock_issue, mock_output_dir, mock_llm_config-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses- mock_get.return_value = MagicMock(json=lambda: {'default_branch': 'main'})- mock_post.return_value.status_code = 403-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Test that RuntimeError is raised when PR creation fails due to permissions- with pytest.raises(- RuntimeError, match='Failed to create pull request due to missing permissions.'- ):- send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITLAB,- patch_dir=repo_path,- pr_type='ready',- )-- # Assert that the branch was created and pushed- assert mock_run.call_count == 2- mock_post.assert_called_once()---@patch('httpx.post')-@patch('httpx.get')-def test_reply_to_comment(mock_get, mock_post, mock_issue):- # Arrange: set up the test data- token = 'test_token'- comment_id = 'GID/test_comment_id'- reply = 'This is a test reply.'-- # Create an instance of GitlabIssueHandler- handler = GitlabIssueHandler(- owner='test-owner', repo='test-repo', token=token, username='test-user'- )-- mock_get.return_value = MagicMock(- json=lambda: {- 'notes': [- {- 'id': 123,- }- ]- }- )-- # Mock the response from the GraphQL API- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {- 'id': 123,- 'body': 'Openhands fix success summary\n\n\nThis is a test reply.',- 'createdAt': '2024-10-01T12:34:56Z',- }-- mock_post.return_value = mock_response-- # Act: call the function- handler.reply_to_comment(mock_issue.number, comment_id, reply)-- # Assert: check that the POST request was made with the correct parameters- data = {- 'body': 'Openhands fix success summary\n\n\nThis is a test reply.',- 'note_id': 123,- }-- # Check that the correct request was made to the API- mock_post.assert_called_once_with(- f'https://gitlab.com/api/v4/projects/{quote(f"{mock_issue.owner}/{mock_issue.repo}", safe="")}/merge_requests/{mock_issue.number}/discussions/{comment_id.split("/")[-1]}/notes',- headers={- 'Authorization': f'Bearer {token}',- 'Accept': 'application/json',- },- json=data,- )-- # Check that the response status was checked (via response.raise_for_status)- mock_response.raise_for_status.assert_called_once()---@patch('openhands.resolver.send_pull_request.initialize_repo')-@patch('openhands.resolver.send_pull_request.apply_patch')-@patch('openhands.resolver.send_pull_request.update_existing_pull_request')-@patch('openhands.resolver.send_pull_request.make_commit')-def test_process_single_pr_update(- mock_make_commit,- mock_update_existing_pull_request,- mock_apply_patch,- mock_initialize_repo,- mock_output_dir,- mock_llm_config,-):- # Initialize test data- token = 'test_token'- username = 'test_user'- pr_type = 'draft'-- resolver_output = ResolverOutput(- issue=Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Issue 1',- body='Body 1',- closing_issues=[],- review_threads=[- ReviewThread(comment='review comment for feedback', files=[])- ],- thread_ids=['1'],- head_branch='branch 1',- ),- issue_type='pr',- instruction='Test instruction 1',- base_commit='def456',- git_patch='Test patch 1',- history=[],- metrics={},- success=True,- comment_success=None,- result_explanation='[Test success 1]',- error=None,- )-- mock_update_existing_pull_request.return_value = (- 'https://gitlab.com/test-owner/test-repo/-/merge_requests/1'- )- mock_initialize_repo.return_value = f'{mock_output_dir}/patches/pr_1'-- process_single_issue(- mock_output_dir,- resolver_output,- token,- username,- ProviderType.GITLAB,- pr_type,- mock_llm_config,- None,- False,- None,- None,- None,- None,- 'openhands',- '[email protected]',- )-- mock_initialize_repo.assert_called_once_with(mock_output_dir, 1, 'pr', 'branch 1')- mock_apply_patch.assert_called_once_with(- f'{mock_output_dir}/patches/pr_1', resolver_output.git_patch- )- mock_make_commit.assert_called_once_with(- f'{mock_output_dir}/patches/pr_1',- resolver_output.issue,- 'pr',- 'openhands',- '[email protected]',- )- mock_update_existing_pull_request.assert_called_once_with(- issue=resolver_output.issue,- token=token,- username=username,- platform=ProviderType.GITLAB,- patch_dir=f'{mock_output_dir}/patches/pr_1',- additional_message='[Test success 1]',- llm_config=mock_llm_config,- base_domain='gitlab.com',- )---@patch('openhands.resolver.send_pull_request.initialize_repo')-@patch('openhands.resolver.send_pull_request.apply_patch')-@patch('openhands.resolver.send_pull_request.send_pull_request')-@patch('openhands.resolver.send_pull_request.make_commit')-def test_process_single_issue(- mock_make_commit,- mock_send_pull_request,- mock_apply_patch,- mock_initialize_repo,- mock_output_dir,- mock_llm_config,-):- # Initialize test data- token = 'test_token'- username = 'test_user'- pr_type = 'draft'- platform = ProviderType.GITLAB-- resolver_output = ResolverOutput(- issue=Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Issue 1',- body='Body 1',- ),- issue_type='issue',- instruction='Test instruction 1',- base_commit='def456',- git_patch='Test patch 1',- history=[],- metrics={},- success=True,- comment_success=None,- result_explanation='Test success 1',- error=None,- )-- # Mock return value- mock_send_pull_request.return_value = (- 'https://gitlab.com/test-owner/test-repo/-/merge_requests/1'- )- mock_initialize_repo.return_value = f'{mock_output_dir}/patches/issue_1'-- # Call the function- process_single_issue(- mock_output_dir,- resolver_output,- token,- username,- platform,- pr_type,- mock_llm_config,- None,- False,- None,- None,- None,- None,- 'openhands',- '[email protected]',- )-- # Assert that the mocked functions were called with correct arguments- mock_initialize_repo.assert_called_once_with(mock_output_dir, 1, 'issue', 'def456')- mock_apply_patch.assert_called_once_with(- f'{mock_output_dir}/patches/issue_1', resolver_output.git_patch- )- mock_make_commit.assert_called_once_with(- f'{mock_output_dir}/patches/issue_1',- resolver_output.issue,- 'issue',- 'openhands',- '[email protected]',- )- mock_send_pull_request.assert_called_once_with(- issue=resolver_output.issue,- token=token,- username=username,- platform=platform,- patch_dir=f'{mock_output_dir}/patches/issue_1',- pr_type=pr_type,- fork_owner=None,- additional_message=resolver_output.result_explanation,- target_branch=None,- reviewer=None,- pr_title=None,- base_domain='gitlab.com',- git_user_name='openhands',- git_user_email='[email protected]',- )---@patch('openhands.resolver.send_pull_request.initialize_repo')-@patch('openhands.resolver.send_pull_request.apply_patch')-@patch('openhands.resolver.send_pull_request.send_pull_request')-@patch('openhands.resolver.send_pull_request.make_commit')-def test_process_single_issue_unsuccessful(- mock_make_commit,- mock_send_pull_request,- mock_apply_patch,- mock_initialize_repo,- mock_output_dir,- mock_llm_config,-):- # Initialize test data- token = 'test_token'- username = 'test_user'- pr_type = 'draft'-- resolver_output = ResolverOutput(- issue=Issue(- owner='test-owner',- repo='test-repo',- number=1,- title='Issue 1',- body='Body 1',- ),- issue_type='issue',- instruction='Test instruction 1',- base_commit='def456',- git_patch='Test patch 1',- history=[],- metrics={},- success=False,- comment_success=None,- result_explanation='',- error='Test error',- )-- # Call the function- process_single_issue(- mock_output_dir,- resolver_output,- token,- username,- ProviderType.GITLAB,- pr_type,- mock_llm_config,- None,- False,- None,- None,- None,- None,- 'openhands',- '[email protected]',- )-- # Assert that none of the mocked functions were called- mock_initialize_repo.assert_not_called()- mock_apply_patch.assert_not_called()- mock_make_commit.assert_not_called()- mock_send_pull_request.assert_not_called()---@patch('httpx.get')-@patch('subprocess.run')-def test_send_pull_request_branch_naming(- mock_run, mock_get, mock_issue, mock_output_dir, mock_llm_config-):- repo_path = os.path.join(mock_output_dir, 'repo')-- # Mock API responses- mock_get.side_effect = [- MagicMock(status_code=200), # First branch exists- MagicMock(status_code=200), # Second branch exists- MagicMock(status_code=404), # Third branch doesn't exist- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- MagicMock(json=lambda: {'default_branch': 'main'}), # Get default branch- ]-- # Mock subprocess.run calls- mock_run.side_effect = [- MagicMock(returncode=0), # git checkout -b- MagicMock(returncode=0), # git push- ]-- # Call the function- result = send_pull_request(- issue=mock_issue,- token='test-token',- username='test-user',- platform=ProviderType.GITLAB,- patch_dir=repo_path,- pr_type='branch',- )-- # Assert API calls- assert mock_get.call_count == 5-- # Check branch creation and push- assert mock_run.call_count == 2- checkout_call, push_call = mock_run.call_args_list-- assert checkout_call == call(- ['git', '-C', repo_path, 'checkout', '-b', 'openhands-fix-issue-42-try3'],- capture_output=True,- text=True,- )- assert push_call == call(- [- 'git',- '-C',- repo_path,- 'push',- 'https://test-user:[email protected]/test-owner/test-repo.git',- 'openhands-fix-issue-42-try3',- ],- capture_output=True,- text=True,- )-- # Check the result- assert (- result- == 'https://gitlab.com/test-owner/test-repo/-/compare/main...openhands-fix-issue-42-try3'- )---@patch('openhands.resolver.send_pull_request.argparse.ArgumentParser')-@patch('openhands.resolver.send_pull_request.process_single_issue')-@patch('openhands.resolver.send_pull_request.load_single_resolver_output')-@patch('openhands.resolver.send_pull_request.identify_token')-@patch('os.path.exists')-@patch('os.getenv')-def test_main(- mock_getenv,- mock_path_exists,- mock_identify_token,- mock_load_single_resolver_output,- mock_process_single_issue,- mock_parser,-):- # Setup mock parser- mock_args = MagicMock()- mock_args.token = None- mock_args.username = 'mock_username'- mock_args.output_dir = '/mock/output'- mock_args.pr_type = 'draft'- mock_args.issue_number = '42'- mock_args.fork_owner = None- mock_args.send_on_failure = False- mock_args.llm_model = 'mock_model'- mock_args.llm_base_url = 'mock_url'- mock_args.llm_api_key = 'mock_key'- mock_args.target_branch = None- mock_args.reviewer = None- mock_args.pr_title = None- mock_args.selected_repo = None- mock_args.git_user_name = 'openhands'- mock_args.git_user_email = '[email protected]'- mock_parser.return_value.parse_args.return_value = mock_args-- # Setup environment variables- mock_getenv.side_effect = (- lambda key, default=None: 'mock_token' if key == 'GITLAB_TOKEN' else default- )-- # Setup path exists- mock_path_exists.return_value = True-- # Setup mock resolver output- mock_resolver_output = MagicMock()- mock_load_single_resolver_output.return_value = mock_resolver_output-- mock_identify_token.return_value = ProviderType.GITLAB-- # Run main function- main()-- mock_identify_token.assert_called_with('mock_token', mock_args.base_domain)-- llm_config = LLMConfig(- model=mock_args.llm_model,- base_url=mock_args.llm_base_url,- api_key=mock_args.llm_api_key,- )-- # Use any_call instead of assert_called_with for more flexible matching- assert mock_process_single_issue.call_args == call(- '/mock/output',- mock_resolver_output,- 'mock_token',- 'mock_username',- ProviderType.GITLAB,- 'draft',- llm_config,- None,- False,- mock_args.target_branch,- mock_args.reviewer,- mock_args.pr_title,- ANY,- mock_args.git_user_name,- mock_args.git_user_email,- )-- # Other assertions- mock_parser.assert_called_once()- mock_getenv.assert_any_call('GITLAB_TOKEN')- mock_path_exists.assert_called_with('/mock/output')- mock_load_single_resolver_output.assert_called_with('/mock/output/output.jsonl', 42)-- # Test for invalid issue number- mock_args.issue_number = 'invalid'- with pytest.raises(ValueError):- main()-- # Test for invalid token- mock_args.issue_number = '42' # Reset to valid issue number- mock_getenv.side_effect = (- lambda key, default=None: None- ) # Return None for all env vars- with pytest.raises(ValueError, match='token is not set'):- main()---@patch('subprocess.run')-def test_make_commit_escapes_issue_title(mock_subprocess_run):- # Setup- repo_dir = '/path/to/repo'- issue = Issue(- owner='test-owner',- repo='test-repo',- number=42,- title='Issue with "quotes" and $pecial characters',- body='Test body',- )-- # Mock subprocess.run to return success for all calls- mock_subprocess_run.return_value = MagicMock(- returncode=0, stdout='sample output', stderr=''- )-- # Call the function- issue_type = 'issue'- make_commit(repo_dir, issue, issue_type)-- # Assert that subprocess.run was called with the correct arguments- calls = mock_subprocess_run.call_args_list- assert len(calls) == 4 # git config check, git add, git commit-- # Check the git commit call- git_commit_call = calls[3][0][0]- expected_commit_message = (- 'Fix issue #42: Issue with "quotes" and $pecial characters'- )- assert [- 'git',- '-C',- '/path/to/repo',- 'commit',- '-m',- expected_commit_message,- ] == git_commit_call---@patch('subprocess.run')-def test_make_commit_no_changes(mock_subprocess_run):- # Setup- repo_dir = '/path/to/repo'- issue = Issue(- owner='test-owner',- repo='test-repo',- number=42,- title='Issue with no changes',- body='Test body',- )-- # Mock subprocess.run to simulate no changes in the repo- mock_subprocess_run.side_effect = [- MagicMock(returncode=0),- MagicMock(returncode=0),- MagicMock(returncode=1, stdout=''), # git status --porcelain (no changes)- ]-- with pytest.raises(- RuntimeError, match='ERROR: Openhands failed to make code changes.'- ):- make_commit(repo_dir, issue, 'issue')-- # Check that subprocess.run was called for checking git status and add, but not commit- assert mock_subprocess_run.call_count == 3- git_status_call = mock_subprocess_run.call_args_list[2][0][0]- assert f'git -C {repo_dir} status --porcelain' in git_status_call---def test_apply_patch_rename_directory(mock_output_dir):- # Create a sample directory structure- old_dir = os.path.join(mock_output_dir, 'prompts', 'resolve')- os.makedirs(old_dir)-- # Create test files- test_files = [- 'issue-success-check.jinja',- 'pr-feedback-check.jinja',- 'pr-thread-check.jinja',- ]- for filename in test_files:- file_path = os.path.join(old_dir, filename)- with open(file_path, 'w') as f:- f.write(f'Content of {filename}')-- # Create a patch that renames the directory- patch_content = """diff --git a/prompts/resolve/issue-success-check.jinja b/prompts/guess_success/issue-success-check.jinja-similarity index 100%-rename from prompts/resolve/issue-success-check.jinja-rename to prompts/guess_success/issue-success-check.jinja-diff --git a/prompts/resolve/pr-feedback-check.jinja b/prompts/guess_success/pr-feedback-check.jinja-similarity index 100%-rename from prompts/resolve/pr-feedback-check.jinja-rename to prompts/guess_success/pr-feedback-check.jinja-diff --git a/prompts/resolve/pr-thread-check.jinja b/prompts/guess_success/pr-thread-check.jinja-similarity index 100%-rename from prompts/resolve/pr-thread-check.jinja-rename to prompts/guess_success/pr-thread-check.jinja"""-- # Apply the patch- apply_patch(mock_output_dir, patch_content)-- # Check if files were moved correctly- new_dir = os.path.join(mock_output_dir, 'prompts', 'guess_success')- assert not os.path.exists(old_dir), 'Old directory still exists'- assert os.path.exists(new_dir), 'New directory was not created'-- # Check if all files were moved and content preserved- for filename in test_files:- old_path = os.path.join(old_dir, filename)- new_path = os.path.join(new_dir, filename)- assert not os.path.exists(old_path), f'Old file {filename} still exists'- assert os.path.exists(new_path), f'New file {filename} was not created'- with open(new_path, 'r') as f:- content = f.read()- assert content == f'Content of {filename}', f'Content mismatch for {filename}'diff --git a/tests/unit/resolver/mock_output/output.jsonl b/tests/unit/resolver/mock_output/output.jsonldeleted file mode 100644index 3a47e017f3..0000000000--- a/tests/unit/resolver/mock_output/output.jsonl+++ /dev/null@@ -1,2 +0,0 @@-{"issue":{"owner":"neubig","repo":"pr-viewer","number":5,"title":"Add MIT license","body":"We can license this repo under the MIT license."},"issue_type":"issue","instruction":"Please fix the following issue for the repository in /workspace.\nEnvironment has been set up for you to start working. You may assume all necessary tools are installed.\n\n# Problem Statement\nWe can license this repo under the MIT license.\n\nIMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\nYou should NOT modify any existing test case files. If needed, you can add new test cases in a NEW file to reproduce the issue.\nYou SHOULD INCLUDE PROPER INDENTATION in your edit commands.\nWhen you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.","base_commit":"","git_patch":"diff --git a/LICENSE b/LICENSE\r\nnew file mode 100644\r\nindex 0000000..dbf96a3\r\n--- /dev/null\r\n+++ b/LICENSE\r\n@@ -0,0 +1,21 @@\r\n+MIT License\r\n+\r\n+Copyright (c) 2024 [Your Name or Organization Name]\r\n+\r\n+Permission is hereby granted, free of charge, to any person obtaining a copy\r\n+of this software and associated documentation files (the \"Software\"), to deal\r\n+in the Software without restriction, including without limitation the rights\r\n+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n+copies of the Software, and to permit persons to whom the Software is\r\n+furnished to do so, subject to the following conditions:\r\n+\r\n+The above copyright notice and this permission notice shall be included in all\r\n+copies or substantial portions of the Software.\r\n+\r\n+THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n+SOFTWARE.\r\n\\ No newline at end of file","history":[{"content":"Please fix the following issue for the repository in /workspace.\nEnvironment has been set up for you to start working. You may assume all necessary tools are installed.\n\n# Problem Statement\nWe can license this repo under the MIT license.\n\nIMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\nYou should NOT modify any existing test case files. If needed, you can add new test cases in a NEW file to reproduce the issue.\nYou SHOULD INCLUDE PROPER INDENTATION in your edit commands.\nWhen you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.","images_urls":null,"wait_for_response":false,"action":"message","action_risk":null},{"command":"touch LICENSE","thought":"Certainly! I'll add the MIT license to the repository in /workspace. Let's start by creating the license file.","keep_prompt":true,"action":"run","is_confirmed":"confirmed","action_risk":null},{"content":"\r\nroot@bcd3959393a1:/workspace # ","command_id":-1,"command":"touch LICENSE","exit_code":0,"observation":"run"},{"code":"mit_license = \"\"\"MIT License\n\nCopyright (c) 2024 [Your Name or Organization Name]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\"\"\"\n\nwith open('LICENSE', 'w') as license_file:\n license_file.write(mit_license)\n\nprint(\"MIT License has been added to the LICENSE file.\")","thought":"Thank you for the reminder. Let's proceed with adding the MIT license content to the LICENSE file.","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"MIT License has been added to the LICENSE file.\n[Jupyter current working directory: /workspace]","code":"mit_license = \"\"\"MIT License\n\nCopyright (c) 2024 [Your Name or Organization Name]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\"\"\"\n\nwith open('LICENSE', 'w') as license_file:\n license_file.write(mit_license)\n\nprint(\"MIT License has been added to the LICENSE file.\")","observation":"run_ipython"},{"command":"cat LICENSE","thought":"Great! We've successfully added the MIT License to the repository. Now, let's verify the contents of the LICENSE file to ensure everything is correct.","keep_prompt":true,"action":"run","is_confirmed":"confirmed","action_risk":null},{"content":"MIT License\r\n\r\nCopyright (c) 2024 [Your Name or Organization Name]\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\nroot@bcd3959393a1:/workspace # ","command_id":-1,"command":"cat LICENSE","exit_code":0,"observation":"run"},{"outputs":{},"thought":"The MIT License has been successfully added to the repository. The content of the LICENSE file is correct and follows the standard MIT License format. \n\nTo complete the task, we should update the copyright line with the appropriate name or organization. Since we don't have specific information about the repository owner, we'll leave it as is for now. If needed, the repository owner can update this line later.\n\nNow that we have added the MIT License to the repository, the task is complete. We have successfully licensed the repo under the MIT license.","action":"finish"}],"metrics":{"accumulated_cost":0.070713,"costs":[0.015396,0.019719,0.016742999999999997,0.018855]},"success":true,"comment_success":null,"result_explanation":"The AI agent has successfully added the MIT License to the repository. The LICENSE file has been created with the correct content following the standard MIT License format. While the copyright line could be updated with specific owner information, this is not strictly necessary for the license to be valid and can be done later if needed. The core requirement of licensing the repo under the MIT license has been fulfilled, thus resolving the issue.","error":null}-{"issue":{"owner":"neubig","repo":"pr-viewer","number":1,"title":"Add a toggle for dark mode","body":"It'd be nice if this app could also support dark mode, we can add a toggle that can turn on dark mode.\r\n\r\nThis would require adding a toggle that switches between the different modes to JS, and modifying the css file."},"issue_type": "issue","instruction":"Please fix the following issue for the repository in /workspace.\nEnvironment has been set up for you to start working. You may assume all necessary tools are installed.\n\n# Problem Statement\nIt'd be nice if this app could also support dark mode, we can add a toggle that can turn on dark mode.\r\n\r\nThis would require adding a toggle that switches between the different modes to JS, and modifying the css file.\n\nIMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\nYou should NOT modify any existing test case files. If needed, you can add new test cases in a NEW file to reproduce the issue.\nYou SHOULD INCLUDE PROPER INDENTATION in your edit commands.\nWhen you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.","base_commit":"","git_patch":"diff --git a/src/App.css b/src/App.css\r\nindex b9d355d..b3c4c63 100644\r\n--- a/src/App.css\r\n+++ b/src/App.css\r\n@@ -5,6 +5,17 @@\r\n text-align: center;\r\n }\r\n \r\n+body {\r\n+ background-color: #ffffff;\r\n+ color: #213547;\r\n+ transition: background-color 0.3s, color 0.3s;\r\n+}\r\n+\r\n+body.dark-mode {\r\n+ background-color: #242424;\r\n+ color: #ffffff;\r\n+}\r\n+\r\n .logo {\r\n height: 6em;\r\n padding: 1.5em;\r\n@@ -40,3 +51,29 @@\r\n .read-the-docs {\r\n color: #888;\r\n }\r\n+\r\n+.dark-mode-toggle {\r\n+ position: fixed;\r\n+ top: 20px;\r\n+ right: 20px;\r\n+ background-color: #646cff;\r\n+ color: white;\r\n+ border: none;\r\n+ padding: 10px 20px;\r\n+ border-radius: 5px;\r\n+ cursor: pointer;\r\n+ transition: background-color 0.3s;\r\n+}\r\n+\r\n+.dark-mode-toggle:hover {\r\n+ background-color: #535bf2;\r\n+}\r\n+\r\n+.dark-mode .dark-mode-toggle {\r\n+ background-color: #ffffff;\r\n+ color: #242424;\r\n+}\r\n+\r\n+.dark-mode .dark-mode-toggle:hover {\r\n+ background-color: #e6e6e6;\r\n+}\r\ndiff --git a/src/PullRequestViewer.tsx b/src/PullRequestViewer.tsx\r\nindex 6a8281f..a7598b3 100644\r\n--- a/src/PullRequestViewer.tsx\r\n+++ b/src/PullRequestViewer.tsx\r\n@@ -24,7 +24,8 @@ interface Repo {\r\n const PullRequestViewer: React.FC = () => {\r\n const [repos, setRepos] = useState<Repo[]>([]);\r\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\r\n- const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\r\n+const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\r\n+ const [darkMode, setDarkMode] = useState(false);\r\n \r\n useEffect(() => {\r\n const fetchRepos = async () => {\r\n@@ -80,9 +81,17 @@ const PullRequestViewer: React.FC = () => {\r\n fetchPullRequests();\r\n }, [selectedRepo]);\r\n \r\n+ const toggleDarkMode = () => {\r\n+ setDarkMode(!darkMode);\r\n+ document.body.classList.toggle('dark-mode');\r\n+ };\r\n+\r\n return (\r\n- <div>\r\n+ <div className={darkMode ? 'dark-mode' : ''}>\r\n <h1>Pull Request Viewer</h1>\r\n+ <button onClick={toggleDarkMode}>\r\n+ {darkMode ? 'Light Mode' : 'Dark Mode'}\r\n+ </button>\r\n <Select\r\n options={repos}\r\n value={selectedRepo}","history":[{"content":"Please fix the following issue for the repository in /workspace.\nEnvironment has been set up for you to start working. You may assume all necessary tools are installed.\n\n# Problem Statement\nIt'd be nice if this app could also support dark mode, we can add a toggle that can turn on dark mode.\r\n\r\nThis would require adding a toggle that switches between the different modes to JS, and modifying the css file.\n\nIMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\nYou should NOT modify any existing test case files. If needed, you can add new test cases in a NEW file to reproduce the issue.\nYou SHOULD INCLUDE PROPER INDENTATION in your edit commands.\nWhen you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.","images_urls":null,"wait_for_response":false,"action":"message","action_risk":null},{"command":"ls -R /workspace","thought":"Certainly! I'll add dark mode support to the application by modifying the necessary files. Let's start by examining the current structure of the project.","keep_prompt":true,"action":"run","is_confirmed":"confirmed","action_risk":null},{"content":"/workspace:\r\nREADME.md\t package-lock.json src\t\ttsconfig.node.json\r\neslint.config.js package.json\t tsconfig.app.json\tvite.config.ts\r\nindex.html\t public\t tsconfig.json\r\n\r\n/workspace/public:\r\nvite.svg\r\n\r\n/workspace/src:\r\nApp.css PullRequestViewer.test.tsx assets\tmain.tsx vite-env.d.ts\r\nApp.tsx PullRequestViewer.tsx\t index.css\tsetupTests.ts\r\n\r\n/workspace/src/assets:\r\nreact.svg\r\n\r\nroot@b365937733b2:/workspace # ","command_id":-1,"command":"ls -R /workspace","exit_code":0,"observation":"run"},{"code":"open_file('/workspace/src/App.css')","thought":"Thank you for providing the project structure. Let's start by modifying the necessary files to add dark mode support.\n\nFirst, let's update the CSS file to include dark mode styles:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/App.css (42 lines total)]\n(this is the beginning of the file)\n1|#root {\n2| max-width: 1280px;\n3| margin: 0 auto;\n4| padding: 2rem;\n5| text-align: center;\n6|}\n7|\n8|.logo {\n9| height: 6em;\n10| padding: 1.5em;\n11| will-change: filter;\n12| transition: filter 300ms;\n13|}\n14|.logo:hover {\n15| filter: drop-shadow(0 0 2em #646cffaa);\n16|}\n17|.logo.react:hover {\n18| filter: drop-shadow(0 0 2em #61dafbaa);\n19|}\n20|\n21|@keyframes logo-spin {\n22| from {\n23| transform: rotate(0deg);\n24| }\n25| to {\n26| transform: rotate(360deg);\n27| }\n28|}\n29|\n30|@media (prefers-reduced-motion: no-preference) {\n31| a:nth-of-type(2) .logo {\n32| animation: logo-spin infinite 20s linear;\n33| }\n34|}\n35|\n36|.card {\n37| padding: 2em;\n38|}\n39|\n40|.read-the-docs {\n41| color: #888;\n42|}\n(this is the end of the file)\n[Jupyter current working directory: /workspace]","code":"open_file('/workspace/src/App.css')","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.css',\nto_replace=\"\"\"#root {\n max-width: 1280px;\n margin: 0 auto;\n padding: 2rem;\n text-align: center;\n}\n\n.logo {\n height: 6em;\n padding: 1.5em;\n will-change: filter;\n transition: filter 300ms;\n}\n.logo:hover {\n filter: drop-shadow(0 0 2em #646cffaa);\n}\n.logo.react:hover {\n filter: drop-shadow(0 0 2em #61dafbaa);\n}\n\n@keyframes logo-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n\n@media (prefers-reduced-motion: no-preference) {\n a:nth-of-type(2) .logo {\n animation: logo-spin infinite 20s linear;\n }\n}\n\n.card {\n padding: 2em;\n}\n\n.read-the-docs {\n color: #888;\n}\"\"\",\nnew_content=\"\"\"#root {\n max-width: 1280px;\n margin: 0 auto;\n padding: 2rem;\n text-align: center;\n}\n\nbody {\n background-color: #ffffff;\n color: #213547;\n transition: background-color 0.3s, color 0.3s;\n}\n\nbody.dark-mode {\n background-color: #242424;\n color: #ffffff;\n}\n\n.logo {\n height: 6em;\n padding: 1.5em;\n will-change: filter;\n transition: filter 300ms;\n}\n.logo:hover {\n filter: drop-shadow(0 0 2em #646cffaa);\n}\n.logo.react:hover {\n filter: drop-shadow(0 0 2em #61dafbaa);\n}\n\n@keyframes logo-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n\n@media (prefers-reduced-motion: no-preference) {\n a:nth-of-type(2) .logo {\n animation: logo-spin infinite 20s linear;\n }\n}\n\n.card {\n padding: 2em;\n}\n\n.read-the-docs {\n color: #888;\n}\n\n.dark-mode-toggle {\n position: fixed;\n top: 20px;\n right: 20px;\n background-color: #646cff;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 5px;\n cursor: pointer;\n transition: background-color 0.3s;\n}\n\n.dark-mode-toggle:hover {\n background-color: #535bf2;\n}\n\n.dark-mode .dark-mode-toggle {\n background-color: #ffffff;\n color: #242424;\n}\n\n.dark-mode .dark-mode-toggle:hover {\n background-color: #e6e6e6;\n}\"\"\"\n)","thought":"Let's update the CSS file to include dark mode styles. We'll add a new class for dark mode and modify existing styles:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/App.css (79 lines total after edit)]\n(this is the beginning of the file)\n1|#root {\n2| max-width: 1280px;\n3| margin: 0 auto;\n4| padding: 2rem;\n5| text-align: center;\n6|}\n7|\n8|body {\n9| background-color: #ffffff;\n10| color: #213547;\n11| transition: background-color 0.3s, color 0.3s;\n12|}\n13|\n14|body.dark-mode {\n15| background-color: #242424;\n16| color: #ffffff;\n17|}\n18|\n19|.logo {\n20| height: 6em;\n21| padding: 1.5em;\n22| will-change: filter;\n23| transition: filter 300ms;\n24|}\n25|.logo:hover {\n26| filter: drop-shadow(0 0 2em #646cffaa);\n27|}\n28|.logo.react:hover {\n29| filter: drop-shadow(0 0 2em #61dafbaa);\n30|}\n31|\n32|@keyframes logo-spin {\n33| from {\n34| transform: rotate(0deg);\n35| }\n36| to {\n37| transform: rotate(360deg);\n38| }\n39|}\n40|\n41|@media (prefers-reduced-motion: no-preference) {\n42| a:nth-of-type(2) .logo {\n43| animation: logo-spin infinite 20s linear;\n44| }\n45|}\n46|\n47|.card {\n48| padding: 2em;\n49|}\n50|\n51|.read-the-docs {\n52| color: #888;\n53|}\n54|\n55|.dark-mode-toggle {\n56| position: fixed;\n57| top: 20px;\n58| right: 20px;\n59| background-color: #646cff;\n60| color: white;\n61| border: none;\n62| padding: 10px 20px;\n63| border-radius: 5px;\n64| cursor: pointer;\n65| transition: background-color 0.3s;\n66|}\n67|\n68|.dark-mode-toggle:hover {\n69| background-color: #535bf2;\n70|}\n71|\n72|.dark-mode .dark-mode-toggle {\n73| background-color: #ffffff;\n74| color: #242424;\n75|}\n76|\n77|.dark-mode .dark-mode-toggle:hover {\n78| background-color: #e6e6e6;\n79|}\n(this is the end of the file)\n[File updated (edited at line 1). Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.css',\nto_replace=\"\"\"#root {\n max-width: 1280px;\n margin: 0 auto;\n padding: 2rem;\n text-align: center;\n}\n\n.logo {\n height: 6em;\n padding: 1.5em;\n will-change: filter;\n transition: filter 300ms;\n}\n.logo:hover {\n filter: drop-shadow(0 0 2em #646cffaa);\n}\n.logo.react:hover {\n filter: drop-shadow(0 0 2em #61dafbaa);\n}\n\n@keyframes logo-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n\n@media (prefers-reduced-motion: no-preference) {\n a:nth-of-type(2) .logo {\n animation: logo-spin infinite 20s linear;\n }\n}\n\n.card {\n padding: 2em;\n}\n\n.read-the-docs {\n color: #888;\n}\"\"\",\nnew_content=\"\"\"#root {\n max-width: 1280px;\n margin: 0 auto;\n padding: 2rem;\n text-align: center;\n}\n\nbody {\n background-color: #ffffff;\n color: #213547;\n transition: background-color 0.3s, color 0.3s;\n}\n\nbody.dark-mode {\n background-color: #242424;\n color: #ffffff;\n}\n\n.logo {\n height: 6em;\n padding: 1.5em;\n will-change: filter;\n transition: filter 300ms;\n}\n.logo:hover {\n filter: drop-shadow(0 0 2em #646cffaa);\n}\n.logo.react:hover {\n filter: drop-shadow(0 0 2em #61dafbaa);\n}\n\n@keyframes logo-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n\n@media (prefers-reduced-motion: no-preference) {\n a:nth-of-type(2) .logo {\n animation: logo-spin infinite 20s linear;\n }\n}\n\n.card {\n padding: 2em;\n}\n\n.read-the-docs {\n color: #888;\n}\n\n.dark-mode-toggle {\n position: fixed;\n top: 20px;\n right: 20px;\n background-color: #646cff;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 5px;\n cursor: pointer;\n transition: background-color 0.3s;\n}\n\n.dark-mode-toggle:hover {\n background-color: #535bf2;\n}\n\n.dark-mode .dark-mode-toggle {\n background-color: #ffffff;\n color: #242424;\n}\n\n.dark-mode .dark-mode-toggle:hover {\n background-color: #e6e6e6;\n}\"\"\"\n)","observation":"run_ipython"},{"code":"open_file('/workspace/src/App.tsx')","thought":"The CSS file has been updated successfully. Now, let's modify the App.tsx file to add the dark mode toggle functionality:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/App.tsx (14 lines total)]\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n[Jupyter current working directory: /workspace]","code":"open_file('/workspace/src/App.tsx')","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode');\n } else {\n document.body.classList.remove('dark-mode');\n }\n }, [darkMode]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n };\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","thought":"Thank you for showing me the App.tsx file. Let's modify it to add the dark mode toggle functionality:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:22\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React, { useState, useEffect } from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| const [darkMode, setDarkMode] = useState(false);\n8|\n9| useEffect(() => {\n10| if (darkMode) {\n11| document.body.classList.add('dark-mode');\n12| } else {\n13| document.body.classList.remove('dark-mode');\n14| }\n15| }, [darkMode]);\n16|\n17| const toggleDarkMode = () => {\n18| setDarkMode(!darkMode);\n19| };\n20|\n21| return (\n22| <div className=\"App\">\n23| <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n24| {darkMode ? 'Light Mode' : 'Dark Mode'}\n25| </button>\n26| <PullRequestViewer />\n27| </div>\n28| )\n29|}\n30|\n31|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode');\n } else {\n document.body.classList.remove('dark-mode');\n }\n }, [darkMode]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n };\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode');\n } else {\n document.body.classList.remove('dark-mode');\n }\n }, [darkMode]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n };\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n );\n}\n\nexport default App\"\"\"\n)","thought":"I apologize for the confusion. It seems the edit was not applied due to a syntax error. Let's try to modify the App.tsx file again with the correct syntax:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:22\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React, { useState, useEffect } from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| const [darkMode, setDarkMode] = useState(false);\n8|\n9| useEffect(() => {\n10| if (darkMode) {\n11| document.body.classList.add('dark-mode');\n12| } else {\n13| document.body.classList.remove('dark-mode');\n14| }\n15| }, [darkMode]);\n16|\n17| const toggleDarkMode = () => {\n18| setDarkMode(!darkMode);\n19| };\n20|\n21| return (\n22| <div className=\"App\">\n23| <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n24| {darkMode ? 'Light Mode' : 'Dark Mode'}\n25| </button>\n26| <PullRequestViewer />\n27| </div>\n28| );\n29|}\n30|\n31|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode');\n } else {\n document.body.classList.remove('dark-mode');\n }\n }, [darkMode]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n };\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n );\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode')\n } else {\n document.body.classList.remove('dark-mode')\n }\n }, [darkMode])\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","thought":"I apologize for the confusion. It seems that the file is using a different syntax or formatting. Let's try to modify the App.tsx file again, keeping the original formatting and only adding the necessary changes:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:22\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React, { useState, useEffect } from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| const [darkMode, setDarkMode] = useState(false)\n8|\n9| useEffect(() => {\n10| if (darkMode) {\n11| document.body.classList.add('dark-mode')\n12| } else {\n13| document.body.classList.remove('dark-mode')\n14| }\n15| }, [darkMode])\n16|\n17| const toggleDarkMode = () => {\n18| setDarkMode(!darkMode)\n19| }\n20|\n21| return (\n22| <div className=\"App\">\n23| <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n24| {darkMode ? 'Light Mode' : 'Dark Mode'}\n25| </button>\n26| <PullRequestViewer />\n27| </div>\n28| )\n29|}\n30|\n31|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode')\n } else {\n document.body.classList.remove('dark-mode')\n }\n }, [darkMode])\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App(): JSX.Element {\n const [darkMode, setDarkMode] = useState<boolean>(false)\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode')\n } else {\n document.body.classList.remove('dark-mode')\n }\n }, [darkMode])\n\n const toggleDarkMode = (): void => {\n setDarkMode(!darkMode)\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","thought":"I apologize for the confusion. It seems that the file is using TypeScript, which requires type annotations. Let's modify the App.tsx file with the correct TypeScript syntax:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:22\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React, { useState, useEffect } from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App(): JSX.Element {\n7| const [darkMode, setDarkMode] = useState<boolean>(false)\n8|\n9| useEffect(() => {\n10| if (darkMode) {\n11| document.body.classList.add('dark-mode')\n12| } else {\n13| document.body.classList.remove('dark-mode')\n14| }\n15| }, [darkMode])\n16|\n17| const toggleDarkMode = (): void => {\n18| setDarkMode(!darkMode)\n19| }\n20|\n21| return (\n22| <div className=\"App\">\n23| <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n24| {darkMode ? 'Light Mode' : 'Dark Mode'}\n25| </button>\n26| <PullRequestViewer />\n27| </div>\n28| )\n29|}\n30|\n31|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App(): JSX.Element {\n const [darkMode, setDarkMode] = useState<boolean>(false)\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode')\n } else {\n document.body.classList.remove('dark-mode')\n }\n }, [darkMode])\n\n const toggleDarkMode = (): void => {\n setDarkMode(!darkMode)\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode')\n } else {\n document.body.classList.remove('dark-mode')\n }\n }, [darkMode])\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","thought":"I apologize for the persistent errors. It seems that the TypeScript configuration might be stricter than expected. Let's try a simpler approach without type annotations:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:22\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React, { useState, useEffect } from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| const [darkMode, setDarkMode] = useState(false)\n8|\n9| useEffect(() => {\n10| if (darkMode) {\n11| document.body.classList.add('dark-mode')\n12| } else {\n13| document.body.classList.remove('dark-mode')\n14| }\n15| }, [darkMode])\n16|\n17| const toggleDarkMode = () => {\n18| setDarkMode(!darkMode)\n19| }\n20|\n21| return (\n22| <div className=\"App\">\n23| <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n24| {darkMode ? 'Light Mode' : 'Dark Mode'}\n25| </button>\n26| <PullRequestViewer />\n27| </div>\n28| )\n29|}\n30|\n31|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n useEffect(() => {\n if (darkMode) {\n document.body.classList.add('dark-mode')\n } else {\n document.body.classList.remove('dark-mode')\n }\n }, [darkMode])\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n document.body.classList.toggle('dark-mode')\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","thought":"I apologize for the continued errors. It seems that there might be some configuration issues or restrictions in place. Let's try a minimal change to add the dark mode toggle without modifying the existing structure too much:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:15\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React, { useState } from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| const [darkMode, setDarkMode] = useState(false)\n8|\n9| const toggleDarkMode = () => {\n10| setDarkMode(!darkMode)\n11| document.body.classList.toggle('dark-mode')\n12| }\n13|\n14| return (\n15| <div className=\"App\">\n16| <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n17| {darkMode ? 'Light Mode' : 'Dark Mode'}\n18| </button>\n19| <PullRequestViewer />\n20| </div>\n21| )\n22|}\n23|\n24|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n document.body.classList.toggle('dark-mode')\n }\n\n return (\n <div className=\"App\">\n <button className=\"dark-mode-toggle\" onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n document.body.classList.toggle('dark-mode')\n }\n\n return (\n <div className={`App ${darkMode ? 'dark-mode' : ''}`}>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","thought":"I apologize for the persistent errors. It seems that there might be some strict TypeScript configurations or linting rules in place. Let's try a minimal change that should work with most configurations:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:14\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React, { useState } from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| const [darkMode, setDarkMode] = useState(false)\n8|\n9| const toggleDarkMode = () => {\n10| setDarkMode(!darkMode)\n11| document.body.classList.toggle('dark-mode')\n12| }\n13|\n14| return (\n15| <div className={`App ${darkMode ? 'dark-mode' : ''}`}>\n16| <button onClick={toggleDarkMode}>\n17| {darkMode ? 'Light Mode' : 'Dark Mode'}\n18| </button>\n19| <PullRequestViewer />\n20| </div>\n21| )\n22|}\n23|\n24|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React, { useState } from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const [darkMode, setDarkMode] = useState(false)\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode)\n document.body.classList.toggle('dark-mode')\n }\n\n return (\n <div className={`App ${darkMode ? 'dark-mode' : ''}`}>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const toggleDarkMode = () => {\n document.body.classList.toggle('dark-mode')\n }\n\n return (\n <div className=\"App\">\n <button onClick={toggleDarkMode}>Toggle Dark Mode</button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","thought":"I apologize for the continued errors. It seems that the project might have strict TypeScript or linting configurations that are preventing our changes. Let's try a minimal change that should work with most configurations and avoid potential syntax errors:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n/workspace/src/App.tsx:12\n[This is how your edit would have looked if applied]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| const toggleDarkMode = () => {\n8| document.body.classList.toggle('dark-mode')\n9| }\n10|\n11| return (\n12| <div className=\"App\">\n13| <button onClick={toggleDarkMode}>Toggle Dark Mode</button>\n14| <PullRequestViewer />\n15| </div>\n16| )\n17|}\n18|\n19|export default App\n(this is the end of the file)\n-------------------------------------------------\n\n[This is the original code before your edit]\n-------------------------------------------------\n(this is the beginning of the file)\n1|\n2|import React from 'react'\n3|import './App.css'\n4|import PullRequestViewer from './PullRequestViewer'\n5|\n6|function App() {\n7| return (\n8| <div className=\"App\">\n9| <PullRequestViewer />\n10| </div>\n11| )\n12|}\n13|\n14|export default App\n(this is the end of the file)\n-------------------------------------------------\nYour changes have NOT been applied. Please fix your edit command and try again.\nYou either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\nDO NOT re-run the same failed edit command. Running it again will lead to the same error.\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/App.tsx',\nto_replace=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n return (\n <div className=\"App\">\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\",\nnew_content=\"\"\"\nimport React from 'react'\nimport './App.css'\nimport PullRequestViewer from './PullRequestViewer'\n\nfunction App() {\n const toggleDarkMode = () => {\n document.body.classList.toggle('dark-mode')\n }\n\n return (\n <div className=\"App\">\n <button onClick={toggleDarkMode}>Toggle Dark Mode</button>\n <PullRequestViewer />\n </div>\n )\n}\n\nexport default App\"\"\"\n)","observation":"run_ipython"},{"code":"open_file('/workspace/src/PullRequestViewer.tsx')","thought":"I apologize for the continued errors. It seems that the project has very strict configurations that are preventing even minimal changes. Let's try a different approach by adding the dark mode toggle functionality to the existing PullRequestViewer component instead of modifying the App component.\n\nFirst, let's check the contents of the PullRequestViewer.tsx file:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/PullRequestViewer.tsx (112 lines total)]\n(this is the beginning of the file)\n1|\n2|\n3|\n4|import React, { useState, useEffect } from 'react';\n5|import axios from 'axios';\n6|import { Octokit } from '@octokit/rest';\n7|import Select from 'react-select';\n8|\n9|const octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n10|\n11|interface PullRequest {\n12| title: string;\n13| html_url: string;\n14| user: {\n15| login: string;\n16| };\n17|}\n18|\n19|interface Repo {\n20| value: string;\n21| label: string;\n22|}\n23|\n24|const PullRequestViewer: React.FC = () => {\n25| const [repos, setRepos] = useState<Repo[]>([]);\n26| const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n27| const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n28|\n29| useEffect(() => {\n30| const fetchRepos = async () => {\n31| try {\n32| const response = await octokit.repos.listForOrg({\n33| org: 'OpenDevin',\n34| type: 'all',\n35| });\n36| const repoOptions = response.data.map(repo => ({\n37| value: repo.name,\n38| label: repo.name,\n39| }));\n40| setRepos(repoOptions);\n41| } catch (error) {\n42| console.error('Error fetching repos:', error);\n43| }\n44| };\n45| fetchRepos();\n46| }, []);\n47|\n48| useEffect(() => {\n49| const fetchPullRequests = async () => {\n50| if (selectedRepo) {\n51| try {\n52| let allPullRequests: PullRequest[] = [];\n53| let page = 1;\n54| let hasNextPage = true;\n55|\n56| while (hasNextPage) {\n57| const response = await octokit.pulls.list({\n58| owner: 'OpenDevin',\n59| repo: selectedRepo.value,\n60| state: 'open',\n61| per_page: 100,\n62| page: page,\n63| });\n64|\n65| allPullRequests = [...allPullRequests, ...response.data];\n66|\n67| if (response.data.length < 100) {\n68| hasNextPage = false;\n69| } else {\n70| page++;\n71| }\n72| }\n73|\n74| setPullRequests(allPullRequests);\n75| } catch (error) {\n76| console.error('Error fetching pull requests:', error);\n77| }\n78| }\n79| };\n80| fetchPullRequests();\n81| }, [selectedRepo]);\n82|\n83| return (\n84| <div>\n85| <h1>Pull Request Viewer</h1>\n86| <Select\n87| options={repos}\n88| value={selectedRepo}\n89| onChange={(option) => setSelectedRepo(option as Repo)}\n90| placeholder=\"Select a repository\"\n91| aria-label=\"Select a repository\"\n92| />\n93| {pullRequests.length > 0 ? (\n94| <ul>\n95| {pullRequests.map((pr) => (\n96| <li key={pr.html_url}>\n97| <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n98| {pr.title}\n99| </a>\n100| {' by '}\n(12 more lines below)\n[Jupyter current working directory: /workspace]","code":"open_file('/workspace/src/PullRequestViewer.tsx')","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\"\nimport React, { useState, useEffect } from 'react';\nimport axios from 'axios';\nimport { Octokit } from '@octokit/rest';\nimport Select from 'react-select';\n\nconst octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n\ninterface PullRequest {\n title: string;\n html_url: string;\n user: {\n login: string;\n };\n}\n\ninterface Repo {\n value: string;\n label: string;\n}\n\nconst PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\n\nexport default PullRequestViewer;\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react';\nimport axios from 'axios';\nimport { Octokit } from '@octokit/rest';\nimport Select from 'react-select';\n\nconst octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n\ninterface PullRequest {\n title: string;\n html_url: string;\n user: {\n login: string;\n };\n}\n\ninterface Repo {\n value: string;\n label: string;\n}\n\nconst PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\n\n return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\n\nexport default PullRequestViewer;\"\"\"\n)","thought":"Thank you for showing me the PullRequestViewer.tsx file. Let's modify this file to add the dark mode toggle functionality. We'll add a dark mode toggle button and update the component's styling based on the dark mode state.","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[No exact match found in /workspace/src/PullRequestViewer.tsx for\n```\n\nimport React, { useState, useEffect } from 'react';\nimport axios from 'axios';\nimport { Octokit } from '@octokit/rest';\nimport Select from 'react-select';\n\nconst octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n\ninterface PullRequest {\n title: string;\n html_url: string;\n user: {\n login: string;\n };\n}\n\ninterface Repo {\n value: string;\n label: string;\n}\n\nconst PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\n\nexport default PullRequestViewer;\n```\n]\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\"\nimport React, { useState, useEffect } from 'react';\nimport axios from 'axios';\nimport { Octokit } from '@octokit/rest';\nimport Select from 'react-select';\n\nconst octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n\ninterface PullRequest {\n title: string;\n html_url: string;\n user: {\n login: string;\n };\n}\n\ninterface Repo {\n value: string;\n label: string;\n}\n\nconst PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\n\nexport default PullRequestViewer;\"\"\",\nnew_content=\"\"\"\nimport React, { useState, useEffect } from 'react';\nimport axios from 'axios';\nimport { Octokit } from '@octokit/rest';\nimport Select from 'react-select';\n\nconst octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n\ninterface PullRequest {\n title: string;\n html_url: string;\n user: {\n login: string;\n };\n}\n\ninterface Repo {\n value: string;\n label: string;\n}\n\nconst PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\n\n return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\n\nexport default PullRequestViewer;\"\"\"\n)","observation":"run_ipython"},{"code":"open_file('/workspace/src/PullRequestViewer.tsx')","thought":"I apologize for the confusion. It seems that the content of the PullRequestViewer.tsx file has changed since we last viewed it. Let's try to add the dark mode toggle functionality to the existing file content. First, let's view the current content of the file:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/PullRequestViewer.tsx (112 lines total)]\n(this is the beginning of the file)\n1|\n2|\n3|\n4|import React, { useState, useEffect } from 'react';\n5|import axios from 'axios';\n6|import { Octokit } from '@octokit/rest';\n7|import Select from 'react-select';\n8|\n9|const octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n10|\n11|interface PullRequest {\n12| title: string;\n13| html_url: string;\n14| user: {\n15| login: string;\n16| };\n17|}\n18|\n19|interface Repo {\n20| value: string;\n21| label: string;\n22|}\n23|\n24|const PullRequestViewer: React.FC = () => {\n25| const [repos, setRepos] = useState<Repo[]>([]);\n26| const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n27| const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n28|\n29| useEffect(() => {\n30| const fetchRepos = async () => {\n31| try {\n32| const response = await octokit.repos.listForOrg({\n33| org: 'OpenDevin',\n34| type: 'all',\n35| });\n36| const repoOptions = response.data.map(repo => ({\n37| value: repo.name,\n38| label: repo.name,\n39| }));\n40| setRepos(repoOptions);\n41| } catch (error) {\n42| console.error('Error fetching repos:', error);\n43| }\n44| };\n45| fetchRepos();\n46| }, []);\n47|\n48| useEffect(() => {\n49| const fetchPullRequests = async () => {\n50| if (selectedRepo) {\n51| try {\n52| let allPullRequests: PullRequest[] = [];\n53| let page = 1;\n54| let hasNextPage = true;\n55|\n56| while (hasNextPage) {\n57| const response = await octokit.pulls.list({\n58| owner: 'OpenDevin',\n59| repo: selectedRepo.value,\n60| state: 'open',\n61| per_page: 100,\n62| page: page,\n63| });\n64|\n65| allPullRequests = [...allPullRequests, ...response.data];\n66|\n67| if (response.data.length < 100) {\n68| hasNextPage = false;\n69| } else {\n70| page++;\n71| }\n72| }\n73|\n74| setPullRequests(allPullRequests);\n75| } catch (error) {\n76| console.error('Error fetching pull requests:', error);\n77| }\n78| }\n79| };\n80| fetchPullRequests();\n81| }, [selectedRepo]);\n82|\n83| return (\n84| <div>\n85| <h1>Pull Request Viewer</h1>\n86| <Select\n87| options={repos}\n88| value={selectedRepo}\n89| onChange={(option) => setSelectedRepo(option as Repo)}\n90| placeholder=\"Select a repository\"\n91| aria-label=\"Select a repository\"\n92| />\n93| {pullRequests.length > 0 ? (\n94| <ul>\n95| {pullRequests.map((pr) => (\n96| <li key={pr.html_url}>\n97| <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n98| {pr.title}\n99| </a>\n100| {' by '}\n(12 more lines below)\n[Jupyter current working directory: /workspace]","code":"open_file('/workspace/src/PullRequestViewer.tsx')","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\",\nnew_content=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\n\n return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\"\n)","thought":"Thank you for showing me the current content of the file. Now, let's add the dark mode toggle functionality to the PullRequestViewer component. We'll make the following changes:\n\n1. Add a new state variable for dark mode\n2. Create a function to toggle dark mode\n3. Add a button to toggle dark mode\n4. Update the component's className based on the dark mode state\n\nHere's the updated code:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[No exact match found in /workspace/src/PullRequestViewer.tsx for\n```\nconst PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\n```\n]\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\",\nnew_content=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\n\n return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\",\nnew_content=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\n\n return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\"\n)","thought":"I apologize for the confusion. It seems that the content of the file has changed since we last viewed it. Let's try to add the dark mode toggle functionality by modifying the existing content. We'll add the dark mode state and toggle function, and update the component's return statement.","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[No exact match found in /workspace/src/PullRequestViewer.tsx for\n```\nconst PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\n```\n]\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\",\nnew_content=\"\"\"const PullRequestViewer: React.FC = () => {\n const [repos, setRepos] = useState<Repo[]>([]);\n const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\n\n useEffect(() => {\n const fetchRepos = async () => {\n try {\n const response = await octokit.repos.listForOrg({\n org: 'OpenDevin',\n type: 'all',\n });\n const repoOptions = response.data.map(repo => ({\n value: repo.name,\n label: repo.name,\n }));\n setRepos(repoOptions);\n } catch (error) {\n console.error('Error fetching repos:', error);\n }\n };\n fetchRepos();\n }, []);\n\n useEffect(() => {\n const fetchPullRequests = async () => {\n if (selectedRepo) {\n try {\n let allPullRequests: PullRequest[] = [];\n let page = 1;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const response = await octokit.pulls.list({\n owner: 'OpenDevin',\n repo: selectedRepo.value,\n state: 'open',\n per_page: 100,\n page: page,\n });\n\n allPullRequests = [...allPullRequests, ...response.data];\n\n if (response.data.length < 100) {\n hasNextPage = false;\n } else {\n page++;\n }\n }\n\n setPullRequests(allPullRequests);\n } catch (error) {\n console.error('Error fetching pull requests:', error);\n }\n }\n };\n fetchPullRequests();\n }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\n\n return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\n {pullRequests.length > 0 ? (\n <ul>\n {pullRequests.map((pr) => (\n <li key={pr.html_url}>\n <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n {pr.title}\n </a>\n {' by '}\n {pr.user.login}\n </li>\n ))}\n </ul>\n ) : (\n <p>No pull requests found.</p>\n )}\n </div>\n );\n};\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\",\nnew_content=\"\"\"const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\"\"\"\n)","thought":"I apologize for the confusion. It seems that the content of the file has changed significantly since we last viewed it. Let's try a different approach by adding the dark mode functionality to the existing code without replacing large portions of it. We'll modify the file incrementally:\n\n1. First, let's add the dark mode state:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/PullRequestViewer.tsx (113 lines total after edit)]\n(this is the beginning of the file)\n1|\n2|\n3|\n4|import React, { useState, useEffect } from 'react';\n5|import axios from 'axios';\n6|import { Octokit } from '@octokit/rest';\n7|import Select from 'react-select';\n8|\n9|const octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });\n10|\n11|interface PullRequest {\n12| title: string;\n13| html_url: string;\n14| user: {\n15| login: string;\n16| };\n17|}\n18|\n19|interface Repo {\n20| value: string;\n21| label: string;\n22|}\n23|\n24|const PullRequestViewer: React.FC = () => {\n25| const [repos, setRepos] = useState<Repo[]>([]);\n26| const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n27|const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n28| const [darkMode, setDarkMode] = useState(false);\n29|\n30| useEffect(() => {\n31| const fetchRepos = async () => {\n32| try {\n33| const response = await octokit.repos.listForOrg({\n34| org: 'OpenDevin',\n35| type: 'all',\n36| });\n37| const repoOptions = response.data.map(repo => ({\n38| value: repo.name,\n39| label: repo.name,\n40| }));\n41| setRepos(repoOptions);\n42| } catch (error) {\n43| console.error('Error fetching repos:', error);\n44| }\n45| };\n46| fetchRepos();\n47| }, []);\n48|\n49| useEffect(() => {\n50| const fetchPullRequests = async () => {\n51| if (selectedRepo) {\n52| try {\n53| let allPullRequests: PullRequest[] = [];\n54| let page = 1;\n55| let hasNextPage = true;\n56|\n57| while (hasNextPage) {\n58| const response = await octokit.pulls.list({\n59| owner: 'OpenDevin',\n60| repo: selectedRepo.value,\n61| state: 'open',\n62| per_page: 100,\n63| page: page,\n64| });\n65|\n66| allPullRequests = [...allPullRequests, ...response.data];\n67|\n68| if (response.data.length < 100) {\n69| hasNextPage = false;\n70| } else {\n71| page++;\n72| }\n73| }\n74|\n75| setPullRequests(allPullRequests);\n76| } catch (error) {\n77| console.error('Error fetching pull requests:', error);\n78| }\n79| }\n80| };\n81| fetchPullRequests();\n82| }, [selectedRepo]);\n83|\n84| return (\n85| <div>\n86| <h1>Pull Request Viewer</h1>\n87| <Select\n88| options={repos}\n89| value={selectedRepo}\n90| onChange={(option) => setSelectedRepo(option as Repo)}\n91| placeholder=\"Select a repository\"\n92| aria-label=\"Select a repository\"\n93| />\n94| {pullRequests.length > 0 ? (\n95| <ul>\n96| {pullRequests.map((pr) => (\n97| <li key={pr.html_url}>\n98| <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n99| {pr.title}\n100| </a>\n(13 more lines below)\n[File updated (edited at line 27). Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\",\nnew_content=\"\"\"const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n const [darkMode, setDarkMode] = useState(false);\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\" }, [selectedRepo]);\",\nnew_content=\"\"\" }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\"\"\"\n)","thought":"Thank you for the update. Now let's add the toggle function for dark mode:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/PullRequestViewer.tsx (118 lines total after edit)]\n(18 more lines above)\n19|interface Repo {\n20| value: string;\n21| label: string;\n22|}\n23|\n24|const PullRequestViewer: React.FC = () => {\n25| const [repos, setRepos] = useState<Repo[]>([]);\n26| const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n27|const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n28| const [darkMode, setDarkMode] = useState(false);\n29|\n30| useEffect(() => {\n31| const fetchRepos = async () => {\n32| try {\n33| const response = await octokit.repos.listForOrg({\n34| org: 'OpenDevin',\n35| type: 'all',\n36| });\n37| const repoOptions = response.data.map(repo => ({\n38| value: repo.name,\n39| label: repo.name,\n40| }));\n41| setRepos(repoOptions);\n42| } catch (error) {\n43| console.error('Error fetching repos:', error);\n44| }\n45| };\n46| fetchRepos();\n47| }, []);\n48|\n49| useEffect(() => {\n50| const fetchPullRequests = async () => {\n51| if (selectedRepo) {\n52| try {\n53| let allPullRequests: PullRequest[] = [];\n54| let page = 1;\n55| let hasNextPage = true;\n56|\n57| while (hasNextPage) {\n58| const response = await octokit.pulls.list({\n59| owner: 'OpenDevin',\n60| repo: selectedRepo.value,\n61| state: 'open',\n62| per_page: 100,\n63| page: page,\n64| });\n65|\n66| allPullRequests = [...allPullRequests, ...response.data];\n67|\n68| if (response.data.length < 100) {\n69| hasNextPage = false;\n70| } else {\n71| page++;\n72| }\n73| }\n74|\n75| setPullRequests(allPullRequests);\n76| } catch (error) {\n77| console.error('Error fetching pull requests:', error);\n78| }\n79| }\n80| };\n81| fetchPullRequests();\n82| }, [selectedRepo]);\n83|\n84| const toggleDarkMode = () => {\n85| setDarkMode(!darkMode);\n86| document.body.classList.toggle('dark-mode');\n87| };\n88|\n89| return (\n90| <div>\n91| <h1>Pull Request Viewer</h1>\n92| <Select\n93| options={repos}\n94| value={selectedRepo}\n95| onChange={(option) => setSelectedRepo(option as Repo)}\n96| placeholder=\"Select a repository\"\n97| aria-label=\"Select a repository\"\n98| />\n99| {pullRequests.length > 0 ? (\n100| <ul>\n101| {pullRequests.map((pr) => (\n102| <li key={pr.html_url}>\n103| <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n104| {pr.title}\n105| </a>\n106| {' by '}\n107| {pr.user.login}\n108| </li>\n109| ))}\n110| </ul>\n111| ) : (\n112| <p>No open pull requests found.</p>\n113| )}\n114| </div>\n115| );\n116|};\n117|\n118|export default PullRequestViewer;\n(this is the end of the file)\n[File updated (edited at line 82). Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\" }, [selectedRepo]);\",\nnew_content=\"\"\" }, [selectedRepo]);\n\n const toggleDarkMode = () => {\n setDarkMode(!darkMode);\n document.body.classList.toggle('dark-mode');\n };\"\"\"\n)","observation":"run_ipython"},{"code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\" return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\"\"\",\nnew_content=\"\"\" return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\"\"\"\n)","thought":"Thank you for the update. Now let's add the dark mode toggle button and update the main div to include the dark mode class:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/PullRequestViewer.tsx (121 lines total after edit)]\n(21 more lines above)\n22|}\n23|\n24|const PullRequestViewer: React.FC = () => {\n25| const [repos, setRepos] = useState<Repo[]>([]);\n26| const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);\n27|const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);\n28| const [darkMode, setDarkMode] = useState(false);\n29|\n30| useEffect(() => {\n31| const fetchRepos = async () => {\n32| try {\n33| const response = await octokit.repos.listForOrg({\n34| org: 'OpenDevin',\n35| type: 'all',\n36| });\n37| const repoOptions = response.data.map(repo => ({\n38| value: repo.name,\n39| label: repo.name,\n40| }));\n41| setRepos(repoOptions);\n42| } catch (error) {\n43| console.error('Error fetching repos:', error);\n44| }\n45| };\n46| fetchRepos();\n47| }, []);\n48|\n49| useEffect(() => {\n50| const fetchPullRequests = async () => {\n51| if (selectedRepo) {\n52| try {\n53| let allPullRequests: PullRequest[] = [];\n54| let page = 1;\n55| let hasNextPage = true;\n56|\n57| while (hasNextPage) {\n58| const response = await octokit.pulls.list({\n59| owner: 'OpenDevin',\n60| repo: selectedRepo.value,\n61| state: 'open',\n62| per_page: 100,\n63| page: page,\n64| });\n65|\n66| allPullRequests = [...allPullRequests, ...response.data];\n67|\n68| if (response.data.length < 100) {\n69| hasNextPage = false;\n70| } else {\n71| page++;\n72| }\n73| }\n74|\n75| setPullRequests(allPullRequests);\n76| } catch (error) {\n77| console.error('Error fetching pull requests:', error);\n78| }\n79| }\n80| };\n81| fetchPullRequests();\n82| }, [selectedRepo]);\n83|\n84| const toggleDarkMode = () => {\n85| setDarkMode(!darkMode);\n86| document.body.classList.toggle('dark-mode');\n87| };\n88|\n89| return (\n90| <div className={darkMode ? 'dark-mode' : ''}>\n91| <h1>Pull Request Viewer</h1>\n92| <button onClick={toggleDarkMode}>\n93| {darkMode ? 'Light Mode' : 'Dark Mode'}\n94| </button>\n95| <Select\n96| options={repos}\n97| value={selectedRepo}\n98| onChange={(option) => setSelectedRepo(option as Repo)}\n99| placeholder=\"Select a repository\"\n100| aria-label=\"Select a repository\"\n101| />\n102| {pullRequests.length > 0 ? (\n103| <ul>\n104| {pullRequests.map((pr) => (\n105| <li key={pr.html_url}>\n106| <a href={pr.html_url} target=\"_blank\" rel=\"noopener noreferrer\">\n107| {pr.title}\n108| </a>\n109| {' by '}\n110| {pr.user.login}\n111| </li>\n112| ))}\n113| </ul>\n114| ) : (\n115| <p>No open pull requests found.</p>\n116| )}\n117| </div>\n118| );\n119|};\n120|\n121|export default PullRequestViewer;\n(this is the end of the file)\n[File updated (edited at line 89). Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]\n[Jupyter current working directory: /workspace]","code":"edit_file_by_replace(\n'/workspace/src/PullRequestViewer.tsx',\nto_replace=\"\"\" return (\n <div>\n <h1>Pull Request Viewer</h1>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\"\"\",\nnew_content=\"\"\" return (\n <div className={darkMode ? 'dark-mode' : ''}>\n <h1>Pull Request Viewer</h1>\n <button onClick={toggleDarkMode}>\n {darkMode ? 'Light Mode' : 'Dark Mode'}\n </button>\n <Select\n options={repos}\n value={selectedRepo}\n onChange={(option) => setSelectedRepo(option as Repo)}\n placeholder=\"Select a repository\"\n aria-label=\"Select a repository\"\n />\"\"\"\n)","observation":"run_ipython"},{"code":"open_file('/workspace/src/App.css')","thought":"The changes have been successfully applied to the PullRequestViewer.tsx file. We have added the dark mode functionality as requested. Now, let's update the App.css file to include the dark mode styles:","action":"run_ipython","is_confirmed":"confirmed","action_risk":null,"kernel_init_code":"from agentskills import *"},{"content":"[File: /workspace/src/App.css (79 lines total)]\n(this is the beginning of the file)\n1|#root {\n2| max-width: 1280px;\n3| margin: 0 auto;\n4| padding: 2rem;\n5| text-align: center;\n6|}\n7|\n8|body {\n9| background-color: #ffffff;\n10| color: #213547;\n11| transition: background-color 0.3s, color 0.3s;\n12|}\n13|\n14|body.dark-mode {\n15| background-color: #242424;\n16| color: #ffffff;\n17|}\n18|\n19|.logo {\n20| height: 6em;\n21| padding: 1.5em;\n22| will-change: filter;\n23| transition: filter 300ms;\n24|}\n25|.logo:hover {\n26| filter: drop-shadow(0 0 2em #646cffaa);\n27|}\n28|.logo.react:hover {\n29| filter: drop-shadow(0 0 2em #61dafbaa);\n30|}\n31|\n32|@keyframes logo-spin {\n33| from {\n34| transform: rotate(0deg);\n35| }\n36| to {\n37| transform: rotate(360deg);\n38| }\n39|}\n40|\n41|@media (prefers-reduced-motion: no-preference) {\n42| a:nth-of-type(2) .logo {\n43| animation: logo-spin infinite 20s linear;\n44| }\n45|}\n46|\n47|.card {\n48| padding: 2em;\n49|}\n50|\n51|.read-the-docs {\n52| color: #888;\n53|}\n54|\n55|.dark-mode-toggle {\n56| position: fixed;\n57| top: 20px;\n58| right: 20px;\n59| background-color: #646cff;\n60| color: white;\n61| border: none;\n62| padding: 10px 20px;\n63| border-radius: 5px;\n64| cursor: pointer;\n65| transition: background-color 0.3s;\n66|}\n67|\n68|.dark-mode-toggle:hover {\n69| background-color: #535bf2;\n70|}\n71|\n72|.dark-mode .dark-mode-toggle {\n73| background-color: #ffffff;\n74| color: #242424;\n75|}\n76|\n77|.dark-mode .dark-mode-toggle:hover {\n78| background-color: #e6e6e6;\n79|}\n(this is the end of the file)\n[Jupyter current working directory: /workspace]","code":"open_file('/workspace/src/App.css')","observation":"run_ipython"},{"outputs":{},"thought":"The App.css file already contains the necessary styles for dark mode. We don't need to make any changes to this file. The dark mode functionality has been successfully implemented in the PullRequestViewer component.\n\nTo summarize the changes we've made:\n\n1. We added a dark mode state to the PullRequestViewer component.\n2. We implemented a toggleDarkMode function to switch between light and dark modes.\n3. We added a button to toggle dark mode in the component's render method.\n4. We updated the main div to include the dark-mode class when dark mode is active.\n\nThe existing CSS styles in App.css will handle the appearance changes for dark mode.\n\nThe task of adding dark mode support to the application has been completed. The toggle can now turn on and off dark mode as requested.","action":"finish"}],"metrics":{"accumulated_cost":1.152933,"costs":[0.015645,0.016581,0.029745,0.022647,0.027885,0.0309,0.033864000000000005,0.036774,0.039504,0.041799,0.044382000000000005,0.046148999999999996,0.045693,0.07552500000000001,0.057120000000000004,0.083457,0.09005099999999999,0.075882,0.078789,0.084789,0.085836,0.089916]},"success":true,"comment_success":null,"result_explanation":"The AI agent has successfully implemented the dark mode functionality as requested. They added a toggle to switch between light and dark modes in the PullRequestViewer component, created the necessary state and function to handle the mode switching, and ensured that the existing CSS in App.css will apply the appropriate styles. The agent confirms that the dark mode can be turned on and off using the newly added toggle, which directly addresses the requirements specified in the issue description.","error":null}diff --git a/tests/unit/resolver/mock_output/repo/src/App.css b/tests/unit/resolver/mock_output/repo/src/App.cssdeleted file mode 100644index b9d355df2a..0000000000--- a/tests/unit/resolver/mock_output/repo/src/App.css+++ /dev/null@@ -1,42 +0,0 @@-#root {- max-width: 1280px;- margin: 0 auto;- padding: 2rem;- text-align: center;-}--.logo {- height: 6em;- padding: 1.5em;- will-change: filter;- transition: filter 300ms;-}-.logo:hover {- filter: drop-shadow(0 0 2em #646cffaa);-}-.logo.react:hover {- filter: drop-shadow(0 0 2em #61dafbaa);-}--@keyframes logo-spin {- from {- transform: rotate(0deg);- }- to {- transform: rotate(360deg);- }-}--@media (prefers-reduced-motion: no-preference) {- a:nth-of-type(2) .logo {- animation: logo-spin infinite 20s linear;- }-}--.card {- padding: 2em;-}--.read-the-docs {- color: #888;-}diff --git a/tests/unit/resolver/mock_output/repo/src/App.tsx b/tests/unit/resolver/mock_output/repo/src/App.tsxdeleted file mode 100644index c3dd99ca1b..0000000000--- a/tests/unit/resolver/mock_output/repo/src/App.tsx+++ /dev/null@@ -1,14 +0,0 @@--import React from 'react'-import './App.css'-import PullRequestViewer from './PullRequestViewer'--function App() {- return (- <div className="App">- <PullRequestViewer />- </div>- )-}--export default Appdiff --git a/tests/unit/resolver/mock_output/repo/src/PullRequestViewer.test.tsx b/tests/unit/resolver/mock_output/repo/src/PullRequestViewer.test.tsxdeleted file mode 100644index 10f29598b5..0000000000--- a/tests/unit/resolver/mock_output/repo/src/PullRequestViewer.test.tsx+++ /dev/null@@ -1,19 +0,0 @@---import React from 'react';-import { render, screen } from '@testing-library/react';-import PullRequestViewer from './PullRequestViewer';--describe('PullRequestViewer', () => {- it('renders the component title', () => {- render(<PullRequestViewer />);- const titleElement = screen.getByText(/Pull Request Viewer/i);- expect(titleElement).toBeInTheDocument();- });-- it('renders the repository select dropdown', () => {- render(<PullRequestViewer />);- const selectElement = screen.getByRole('combobox', { name: /select a repository/i });- expect(selectElement).toBeInTheDocument();- });-});diff --git a/tests/unit/resolver/mock_output/repo/src/PullRequestViewer.tsx b/tests/unit/resolver/mock_output/repo/src/PullRequestViewer.tsxdeleted file mode 100644index 6a8281f7af..0000000000--- a/tests/unit/resolver/mock_output/repo/src/PullRequestViewer.tsx+++ /dev/null@@ -1,112 +0,0 @@----import React, { useState, useEffect } from 'react';-import axios from 'axios';-import { Octokit } from '@octokit/rest';-import Select from 'react-select';--const octokit = new Octokit({ auth: import.meta.env.VITE_GITHUB_TOKEN });--interface PullRequest {- title: string;- html_url: string;- user: {- login: string;- };-}--interface Repo {- value: string;- label: string;-}--const PullRequestViewer: React.FC = () => {- const [repos, setRepos] = useState<Repo[]>([]);- const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null);- const [pullRequests, setPullRequests] = useState<PullRequest[]>([]);-- useEffect(() => {- const fetchRepos = async () => {- try {- const response = await octokit.repos.listForOrg({- org: 'OpenDevin',- type: 'all',- });- const repoOptions = response.data.map(repo => ({- value: repo.name,- label: repo.name,- }));- setRepos(repoOptions);- } catch (error) {- console.error('Error fetching repos:', error);- }- };- fetchRepos();- }, []);-- useEffect(() => {- const fetchPullRequests = async () => {- if (selectedRepo) {- try {- let allPullRequests: PullRequest[] = [];- let page = 1;- let hasNextPage = true;-- while (hasNextPage) {- const response = await octokit.pulls.list({- owner: 'OpenDevin',- repo: selectedRepo.value,- state: 'open',- per_page: 100,- page: page,- });-- allPullRequests = [...allPullRequests, ...response.data];-- if (response.data.length < 100) {- hasNextPage = false;- } else {- page++;- }- }-- setPullRequests(allPullRequests);- } catch (error) {- console.error('Error fetching pull requests:', error);- }- }- };- fetchPullRequests();- }, [selectedRepo]);-- return (- <div>- <h1>Pull Request Viewer</h1>- <Select- options={repos}- value={selectedRepo}- onChange={(option) => setSelectedRepo(option as Repo)}- placeholder="Select a repository"- aria-label="Select a repository"- />- {pullRequests.length > 0 ? (- <ul>- {pullRequests.map((pr) => (- <li key={pr.html_url}>- <a href={pr.html_url} target="_blank" rel="noopener noreferrer">- {pr.title}- </a>- {' by '}- {pr.user.login}- </li>- ))}- </ul>- ) : (- <p>No open pull requests found.</p>- )}- </div>- );-};--export default PullRequestViewer;diff --git a/tests/unit/resolver/test_issue_handler_factory.py b/tests/unit/resolver/test_issue_handler_factory.pydeleted file mode 100644index 96b513be0a..0000000000--- a/tests/unit/resolver/test_issue_handler_factory.py+++ /dev/null@@ -1,156 +0,0 @@-import pytest-from pydantic import SecretStr--from openhands.core.config import LLMConfig-from openhands.integrations.provider import ProviderType-from openhands.resolver.interfaces.azure_devops import AzureDevOpsIssueHandler-from openhands.resolver.interfaces.forgejo import (- ForgejoIssueHandler,- ForgejoPRHandler,-)-from openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandler-from openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandler-from openhands.resolver.interfaces.issue_definitions import (- ServiceContextIssue,- ServiceContextPR,-)-from openhands.resolver.issue_handler_factory import IssueHandlerFactory---def llm_config():- return LLMConfig(- model='test-model',- api_key=SecretStr('test-key'),- )---def factory_params(llm_config):- return {- 'owner': 'test-owner',- 'repo': 'test-repo',- 'token': 'test-token',- 'username': 'test-user',- 'llm_config': llm_config,- }---def azure_factory_params(llm_config):- return {- 'owner': 'test-org/test-project',- 'repo': 'test-repo',- 'token': 'test-token',- 'username': 'test-user',- 'base_domain': 'dev.azure.com',- 'llm_config': llm_config,- }---test_cases = [- # platform, issue_type, base_domain, expected_context_type, expected_handler_type, use_azure_params- (- ProviderType.GITHUB,- 'issue',- 'github.com',- ServiceContextIssue,- GithubIssueHandler,- False,- ),- (- ProviderType.GITHUB,- 'pr',- 'github.com',- ServiceContextPR,- GithubPRHandler,- False,- ),- (- ProviderType.GITLAB,- 'issue',- 'gitlab.com',- ServiceContextIssue,- GitlabIssueHandler,- False,- ),- (- ProviderType.GITLAB,- 'pr',- 'gitlab.com',- ServiceContextPR,- GitlabPRHandler,- False,- ),- (- ProviderType.FORGEJO,- 'issue',- 'codeberg.org',- ServiceContextIssue,- ForgejoIssueHandler,- False,- ),- (- ProviderType.FORGEJO,- 'pr',- 'codeberg.org',- ServiceContextPR,- ForgejoPRHandler,- False,- ),- (- ProviderType.AZURE_DEVOPS,- 'issue',- 'dev.azure.com',- ServiceContextIssue,- AzureDevOpsIssueHandler,- True,- ),- (- ProviderType.AZURE_DEVOPS,- 'pr',- 'dev.azure.com',- ServiceContextPR,- AzureDevOpsIssueHandler,- True,- ),-]--- 'platform,issue_type,base_domain,expected_context_type,expected_handler_type,use_azure_params',- test_cases,-)-def test_handler_creation(- factory_params,- azure_factory_params,- platform: ProviderType,- issue_type: str,- base_domain: str,- expected_context_type: type,- expected_handler_type: type,- use_azure_params: bool,-):- params = (- azure_factory_params- if use_azure_params- else {**factory_params, 'base_domain': base_domain}- )- factory = IssueHandlerFactory(**params, platform=platform, issue_type=issue_type)-- handler = factory.create()-- assert isinstance(handler, expected_context_type)- assert isinstance(handler._strategy, expected_handler_type)---def test_invalid_issue_type(factory_params):- factory = IssueHandlerFactory(- **factory_params,- platform=ProviderType.GITHUB,- issue_type='invalid',- base_domain='github.com',- )-- with pytest.raises(ValueError, match='Invalid issue type: invalid'):- factory.create()diff --git a/tests/unit/resolver/test_issue_references.py b/tests/unit/resolver/test_issue_references.pydeleted file mode 100644index 0a117492bf..0000000000--- a/tests/unit/resolver/test_issue_references.py+++ /dev/null@@ -1,56 +0,0 @@-from openhands.resolver.utils import extract_issue_references---def test_extract_issue_references():- # Test basic issue reference- assert extract_issue_references('Fixes #123') == [123]-- # Test multiple issue references- assert extract_issue_references('Fixes #123, #456') == [123, 456]-- # Test issue references in code blocks should be ignored- assert extract_issue_references("""- Here's a code block:- ```python- # This is a comment with #123- def func():- pass # Another #456- ```- But this #789 should be extracted- """) == [789]-- # Test issue references in inline code should be ignored- assert extract_issue_references(- 'This `#123` should be ignored but #456 should be extracted'- ) == [456]- assert extract_issue_references(- 'This `#123` should be ignored but #456 should be extracted'- ) == [456]-- # Test issue references in URLs should be ignored- assert extract_issue_references(- 'Check http://example.com/#123 but #456 should be extracted'- ) == [456]- assert extract_issue_references(- 'Check http://example.com/#123 but #456 should be extracted'- ) == [456]-- # Test issue references in markdown links should be extracted- assert extract_issue_references('[Link to #123](http://example.com) and #456') == [- 123,- 456,- ]- assert extract_issue_references('[Link to #123](http://example.com) and #456') == [- 123,- 456,- ]-- # Test issue references with text around them- assert extract_issue_references('Issue #123 is fixed and #456 is pending') == [- 123,- 456,- ]- assert extract_issue_references('Issue #123 is fixed and #456 is pending') == [- 123,- 456,- ]diff --git a/tests/unit/resolver/test_patch_apply.py b/tests/unit/resolver/test_patch_apply.pydeleted file mode 100644index 4360f1dcd2..0000000000--- a/tests/unit/resolver/test_patch_apply.py+++ /dev/null@@ -1,47 +0,0 @@-from openhands.resolver.patching.apply import apply_diff-from openhands.resolver.patching.patch import diffobj, parse_diff---def test_patch_apply_with_empty_lines():- # The original file has no indentation and uses \n line endings- original_content = '# PR Viewer\n\nThis React application allows you to view open pull requests from GitHub repositories in a GitHub organization. By default, it uses the OpenHands organization.\n\n## Setup'-- # The patch has spaces at the start of each line and uses \n line endings- patch = """diff --git a/README.md b/README.md-index b760a53..5071727 100644---- a/README.md-+++ b/README.md-@@ -1,3 +1,3 @@- # PR Viewer---This React application allows you to view open pull requests from GitHub repositories in a GitHub organization. By default, it uses the OpenHands organization.-+This React application was created by Graham Neubig and OpenHands. It allows you to view open pull requests from GitHub repositories in a GitHub organization. By default, it uses the OpenHands organization."""-- print('Original content lines:')- for i, line in enumerate(original_content.splitlines(), 1):- print(f'{i}: {repr(line)}')-- print('\nPatch lines:')- for i, line in enumerate(patch.splitlines(), 1):- print(f'{i}: {repr(line)}')-- changes = parse_diff(patch)- print('\nParsed changes:')- for change in changes:- print(- f'Change(old={change.old}, new={change.new}, line={repr(change.line)}, hunk={change.hunk})'- )- diff = diffobj(header=None, changes=changes, text=patch)-- # Apply the patch- result = apply_diff(diff, original_content)-- # The patch should be applied successfully- expected_result = [- '# PR Viewer',- '',- 'This React application was created by Graham Neubig and OpenHands. It allows you to view open pull requests from GitHub repositories in a GitHub organization. By default, it uses the OpenHands organization.',- '',- '## Setup',- ]- assert result == expected_resultdiff --git a/tests/unit/resolver/test_patch_whitespace.py b/tests/unit/resolver/test_patch_whitespace.pydeleted file mode 100644index 197584f4e7..0000000000--- a/tests/unit/resolver/test_patch_whitespace.py+++ /dev/null@@ -1,79 +0,0 @@-from openhands.resolver.patching.apply import apply_diff-from openhands.resolver.patching.patch import parse_patch---def test_patch_whitespace_mismatch():- """Test that the patch application succeeds even when whitespace doesn't match."""- # Original content has a line with spaces- original_content = """class Example:- def method(self):- pass-- def another(self):- pass"""-- # Patch expects an empty line (no spaces)- patch_text = """diff --git a/example.py b/example.py-index 1234567..89abcdef 100644---- a/example.py-+++ b/example.py-@@ -2,6 +2,10 @@ class Example:- def method(self):- pass--+ new_field: str = "value"-+- def another(self):- pass"""-- patch = next(parse_patch(patch_text))- # The patch should still work because we normalize whitespace- new_content = apply_diff(patch, original_content)- assert new_content == [- 'class Example:',- ' def method(self):',- ' pass',- '',- ' new_field: str = "value"',- '',- ' def another(self):',- ' pass',- ]---def test_patch_whitespace_match():- """Test that the patch application succeeds when whitespace matches."""- # Original content has an empty line (no spaces)- original_content = """class Example:- def method(self):- pass-- def another(self):- pass"""-- # Patch expects an empty line (no spaces)- patch_text = """diff --git a/example.py b/example.py-index 1234567..89abcdef 100644---- a/example.py-+++ b/example.py-@@ -2,6 +2,10 @@ class Example:- def method(self):- pass--+ new_field: str = "value"-+- def another(self):- pass"""-- patch = next(parse_patch(patch_text))- new_content = apply_diff(patch, original_content)- assert new_content == [- 'class Example:',- ' def method(self):',- ' pass',- '',- ' new_field: str = "value"',- '',- ' def another(self):',- ' pass',- ]diff --git a/tests/unit/resolver/test_resolve_issue.py b/tests/unit/resolver/test_resolve_issue.pydeleted file mode 100644index e391913cbb..0000000000--- a/tests/unit/resolver/test_resolve_issue.py+++ /dev/null@@ -1,181 +0,0 @@-from unittest import mock--import pytest--from openhands.core.config import OpenHandsConfig, SandboxConfig-from openhands.events.action import CmdRunAction-from openhands.resolver.issue_resolver import IssueResolver---def assert_sandbox_config(- config: SandboxConfig,- base_container_image=SandboxConfig.model_fields['base_container_image'].default,- runtime_container_image='ghcr.io/openhands/runtime:mock-nikolaik', # Default to mock version- local_runtime_url=SandboxConfig.model_fields['local_runtime_url'].default,- enable_auto_lint=False,-):- """Helper function to assert the properties of the SandboxConfig object."""- assert isinstance(config, SandboxConfig)- assert config.base_container_image == base_container_image- assert config.runtime_container_image == runtime_container_image- assert config.enable_auto_lint is enable_auto_lint- assert config.use_host_network is False- assert config.timeout == 300- assert config.local_runtime_url == local_runtime_url---def test_setup_sandbox_config_default():- """Test default configuration when no images provided and not experimental"""- with mock.patch('openhands.__version__', 'mock'):- openhands_config = OpenHandsConfig()-- IssueResolver.update_sandbox_config(- openhands_config=openhands_config,- base_container_image=None,- runtime_container_image=None,- is_experimental=False,- )-- assert_sandbox_config(- openhands_config.sandbox,- runtime_container_image='ghcr.io/openhands/runtime:mock-nikolaik',- )---def test_setup_sandbox_config_both_images():- """Test that providing both container images raises ValueError"""- with pytest.raises(- ValueError, match='Cannot provide both runtime and base container images.'- ):- openhands_config = OpenHandsConfig()-- IssueResolver.update_sandbox_config(- openhands_config=openhands_config,- base_container_image='base-image',- runtime_container_image='runtime-image',- is_experimental=False,- )---def test_setup_sandbox_config_base_only():- """Test configuration when only base_container_image is provided"""- base_image = 'custom-base-image'- openhands_config = OpenHandsConfig()-- IssueResolver.update_sandbox_config(- openhands_config=openhands_config,- base_container_image=base_image,- runtime_container_image=None,- is_experimental=False,- )-- assert_sandbox_config(- openhands_config.sandbox,- base_container_image=base_image,- runtime_container_image=None,- )---def test_setup_sandbox_config_runtime_only():- """Test configuration when only runtime_container_image is provided"""- runtime_image = 'custom-runtime-image'- openhands_config = OpenHandsConfig()-- IssueResolver.update_sandbox_config(- openhands_config=openhands_config,- base_container_image=None,- runtime_container_image=runtime_image,- is_experimental=False,- )-- assert_sandbox_config(- openhands_config.sandbox, runtime_container_image=runtime_image- )---def test_setup_sandbox_config_experimental():- """Test configuration when experimental mode is enabled"""- with mock.patch('openhands.__version__', 'mock'):- openhands_config = OpenHandsConfig()-- IssueResolver.update_sandbox_config(- openhands_config=openhands_config,- base_container_image=None,- runtime_container_image=None,- is_experimental=True,- )-- assert_sandbox_config(openhands_config.sandbox, runtime_container_image=None)--[email protected]('openhands.resolver.issue_resolver.os.getuid', return_value=0)[email protected]('openhands.resolver.issue_resolver.get_unique_uid', return_value=1001)-def test_setup_sandbox_config_gitlab_ci(mock_get_unique_uid, mock_getuid):- """Test GitLab CI specific configuration when running as root"""- with mock.patch('openhands.__version__', 'mock'):- with mock.patch.object(IssueResolver, 'GITLAB_CI', True):- openhands_config = OpenHandsConfig()-- IssueResolver.update_sandbox_config(- openhands_config=openhands_config,- base_container_image=None,- runtime_container_image=None,- is_experimental=False,- )-- assert_sandbox_config(- openhands_config.sandbox, local_runtime_url='http://localhost'- )--[email protected]('openhands.resolver.issue_resolver.os.getuid', return_value=1000)-def test_setup_sandbox_config_gitlab_ci_non_root(mock_getuid):- """Test GitLab CI configuration when not running as root"""- with mock.patch('openhands.__version__', 'mock'):- with mock.patch.object(IssueResolver, 'GITLAB_CI', True):- openhands_config = OpenHandsConfig()-- IssueResolver.update_sandbox_config(- openhands_config=openhands_config,- base_container_image=None,- runtime_container_image=None,- is_experimental=False,- )-- assert_sandbox_config(- openhands_config.sandbox, local_runtime_url='http://localhost'- )--[email protected]('openhands.events.observation.CmdOutputObservation')[email protected]('openhands.runtime.base.Runtime')-def test_initialize_runtime_runs_setup_script_and_git_hooks(- mock_runtime, mock_cmd_output-):- """Test that initialize_runtime calls maybe_run_setup_script and maybe_setup_git_hooks"""-- # Create a minimal resolver instance with just the methods we need- class MinimalResolver:- def initialize_runtime(self, runtime):- # This is the method we're testing- action = CmdRunAction(command='git config --global core.pager ""')- runtime.run_action(action)-- # Run setup script if it exists- runtime.maybe_run_setup_script()-- # Setup git hooks if they exist- runtime.maybe_setup_git_hooks()-- resolver = MinimalResolver()-- # Mock the runtime's run_action method to return a successful CmdOutputObservation- mock_cmd_output.return_value.exit_code = 0- mock_runtime.run_action.return_value = mock_cmd_output.return_value-- # Call the method- resolver.initialize_runtime(mock_runtime)-- # Verify that both methods were called- mock_runtime.maybe_run_setup_script.assert_called_once()- mock_runtime.maybe_setup_git_hooks.assert_called_once()