π OpenHands: AI-Driven Development
[Refactor]: Abstract resolver into classes (#7999)
Rohit Malhotra1c4c477b3f9e
diff --git a/openhands/resolver/resolve_issue.py b/openhands/resolver/resolve_issue.pyindex 03e66accb3..f3ecbba715 100644--- a/openhands/resolver/resolve_issue.py+++ b/openhands/resolver/resolve_issue.py@@ -7,6 +7,7 @@ import osimport pathlibimport shutilimport subprocess+from argparse import Namespacefrom typing import Anyfrom uuid import uuid4@@ -48,500 +49,591 @@ from openhands.utils.async_utils import GENERAL_TIMEOUT, call_async_from_syncAGENT_CLASS = 'CodeActAgent'-def initialize_runtime(- runtime: Runtime,- platform: ProviderType,-) -> None:- """Initialize the runtime for the agent.-- This function is called before the runtime is used to run the agent.- Currently it does nothing.- """- 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 platform == ProviderType.GITLAB and os.getenv('GITLAB_CI') == 'true':- action = CmdRunAction(command='sudo chown -R 1001:0 /workspace/*')+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.+ """++ base_container_image = args.base_container_image+ runtime_container_image = args.runtime_container_image++ 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 args.is_experimental+ ):+ runtime_container_image = (+ f'ghcr.io/all-hands-ai/runtime:{openhands.__version__}-nikolaik'+ )++ 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')+ 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,+ )++ api_key = args.llm_api_key or os.environ['LLM_API_KEY']+ model = args.llm_model or os.environ['LLM_MODEL']+ base_url = args.llm_base_url or os.environ.get('LLM_BASE_URL', None)+ api_version = os.environ.get('LLM_API_VERSION', None)++ # Create LLMConfig instance+ llm_config = LLMConfig(+ model=model,+ api_key=SecretStr(api_key) if api_key else None,+ base_url=base_url,+ )++ # Only set api_version if it was explicitly provided, otherwise let LLMConfig handle it+ if api_version is not None:+ llm_config.api_version = api_version++ 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:+ 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'+ )++ self.owner = owner+ self.repo = repo+ self.token = token+ self.username = username+ self.platform = platform+ self.runtime_container_image = runtime_container_image+ self.base_container_image = base_container_image+ self.max_iterations = args.max_iterations+ self.output_dir = args.output_dir+ self.llm_config = llm_config+ self.prompt_template = prompt_template+ self.issue_type = issue_type+ self.repo_instruction = repo_instruction+ self.issue_number = args.issue_number+ self.comment_id = args.comment_id+ self.base_domain = base_domain+ self.platform = platform++ 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.+ Currently it does nothing.+ """+ 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}')++ 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 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}')---async def complete_runtime(- runtime: Runtime,- base_commit: str,- platform: ProviderType,-) -> 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 --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')- 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 platform == ProviderType.GITLAB and os.getenv('GITLAB_CI') == 'true':- 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...')+ 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)- 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}++ 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:- 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}---async def process_issue(- issue: Issue,- platform: ProviderType,- base_commit: str,- max_iterations: int,- llm_config: LLMConfig,- output_dir: str,- base_container_image: str | None,- runtime_container_image: str | None,- prompt_template: str,- issue_handler: ServiceContextIssue | ServiceContextPR,- repo_instruction: str | None = None,- 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(output_dir, 'infer_logs')- reset_logger_for_multiprocessing(logger, str(issue.number), log_dir)- else:- logger.info(f'Starting fixing issue {issue.number}.')-- workspace_base = os.path.join(- output_dir, 'workspace', f'{issue_handler.issue_type}_{issue.number}'- )+ logger.info(f'Starting fixing issue {issue.number}.')- # Get the absolute path of the workspace base- workspace_base = os.path.abspath(workspace_base)- # write the repo to the workspace- if os.path.exists(workspace_base):- shutil.rmtree(workspace_base)- shutil.copytree(os.path.join(output_dir, 'repo'), workspace_base)-- # This code looks unnecessary because these are default values in the config class- # they're set by default if nothing else overrides them- # FIXME we should remove them here- sandbox_config = SandboxConfig(- base_container_image=base_container_image,- runtime_container_image=runtime_container_image,- enable_auto_lint=False,- use_host_network=False,- # large enough timeout, since some testcases take very long to run- timeout=300,- )+ workspace_base = os.path.join(+ self.output_dir, 'workspace', f'{issue_handler.issue_type}_{issue.number}'+ )- if os.getenv('GITLAB_CI') == 'true':- sandbox_config.local_runtime_url = os.getenv(- 'LOCAL_RUNTIME_URL', 'http://localhost'+ # Get the absolute path of the workspace base+ workspace_base = os.path.abspath(workspace_base)+ # write the repo to the workspace+ if os.path.exists(workspace_base):+ shutil.rmtree(workspace_base)+ shutil.copytree(os.path.join(self.output_dir, 'repo'), workspace_base)++ # This code looks unnecessary because these are default values in the config class+ # they're set by default if nothing else overrides them+ # FIXME we should remove them here+ sandbox_config = SandboxConfig(+ base_container_image=self.base_container_image,+ runtime_container_image=self.runtime_container_image,+ enable_auto_lint=False,+ use_host_network=False,+ # large enough timeout, since some testcases take very long to run+ timeout=300,)- user_id = os.getuid() if hasattr(os, 'getuid') else 1000- if user_id == 0:- sandbox_config.user_id = get_unique_uid()-- config = AppConfig(- default_agent='CodeActAgent',- runtime='docker',- max_budget_per_task=4,- max_iterations=max_iterations,- sandbox=sandbox_config,- # do not mount workspace- workspace_base=workspace_base,- workspace_mount_path=workspace_base,- agents={'CodeActAgent': AgentConfig(disabled_microagents=['github'])},- )- config.set_llm_config(llm_config)- runtime = create_runtime(config)- await runtime.connect()+ if os.getenv('GITLAB_CI') == 'true':+ 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()++ config = AppConfig(+ default_agent='CodeActAgent',+ runtime='docker',+ max_budget_per_task=4,+ max_iterations=self.max_iterations,+ sandbox=sandbox_config,+ # do not mount workspace+ workspace_base=workspace_base,+ workspace_mount_path=workspace_base,+ agents={'CodeActAgent': AgentConfig(disabled_microagents=['github'])},+ )+ config.set_llm_config(self.llm_config)++ runtime = create_runtime(config)+ await runtime.connect()- def on_event(evt: Event) -> None:- logger.info(evt)+ def on_event(evt: Event) -> None:+ logger.info(evt)- runtime.event_stream.subscribe(EventStreamSubscriber.MAIN, on_event, str(uuid4()))+ runtime.event_stream.subscribe(+ EventStreamSubscriber.MAIN, on_event, str(uuid4())+ )- initialize_runtime(runtime, platform)+ self.initialize_runtime(runtime)- instruction, images_urls = issue_handler.get_instruction(- issue, prompt_template, 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=config,- initial_user_action=action,- runtime=runtime,- fake_user_response_fn=codeact_user_response,+ instruction, images_urls = issue_handler.get_instruction(+ issue, self.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=config,+ initial_user_action=action,+ runtime=runtime,+ fake_user_response_fn=codeact_user_response,+ )+ 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 stateif 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 complete_runtime(runtime, base_commit, platform)- git_patch = return_val['git_patch']- logger.info(- f'Got git diff for instance {issue.number}:\n--------\n{git_patch}\n--------'- )+ 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+ )- # 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,)-- 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}'+ return output++ def issue_handler_factory(self) -> ServiceContextIssue | ServiceContextPR:+ # Determine default base_domain based on platform++ 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,)- 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')+ else: # platform == Platform.GITLAB+ return ServiceContextIssue(+ GitlabIssueHandler(+ self.owner,+ self.repo,+ self.token,+ self.username,+ self.base_domain,+ ),+ self.llm_config,)- 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 issue_handler_factory(- issue_type: str,- owner: str,- repo: str,- token: str,- llm_config: LLMConfig,- platform: ProviderType,- username: str | None = None,- base_domain: str | None = None,-) -> ServiceContextIssue | ServiceContextPR:- # Determine default base_domain based on platform- if base_domain is None:- base_domain = 'github.com' if platform == ProviderType.GITHUB else 'gitlab.com'- if issue_type == 'issue':- if platform == ProviderType.GITHUB:- return ServiceContextIssue(- GithubIssueHandler(owner, repo, token, username, base_domain),- llm_config,- )- else: # platform == Platform.GITLAB- return ServiceContextIssue(- GitlabIssueHandler(owner, repo, token, username, base_domain),- llm_config,- )- elif issue_type == 'pr':- if platform == ProviderType.GITHUB:- return ServiceContextPR(- GithubPRHandler(owner, repo, token, username, base_domain), llm_config- )- else: # platform == Platform.GITLAB- return ServiceContextPR(- GitlabPRHandler(owner, repo, token, username, base_domain), llm_config- )- else:- raise ValueError(f'Invalid issue type: {issue_type}')---async def resolve_issue(- owner: str,- repo: str,- token: str,- username: str,- platform: ProviderType,- max_iterations: int,- output_dir: str,- llm_config: LLMConfig,- base_container_image: str | None,- runtime_container_image: str | None,- prompt_template: str,- issue_type: str,- repo_instruction: str | None,- issue_number: int,- comment_id: int | None,- reset_logger: bool = False,- base_domain: str | None = None,-) -> None:- """Resolve a single issue.-- Args:- owner: owner of the repo.- repo: repository to resolve issues in form of `owner/repo`.- token: token to access the repository.- username: username to access the repository.- platform: platform of the repository.- max_iterations: Maximum number of iterations to run.- output_dir: Output directory to write the results.- llm_config: Configuration for the language model.- runtime_container_image: Container image to use.- 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.- reset_logger: Whether to reset the logger for multiprocessing.- base_domain: The base domain for the git server (defaults to "github.com" for GitHub and "gitlab.com" for GitLab)- """- # Determine default base_domain based on platform- if base_domain is None:- base_domain = 'github.com' if platform == ProviderType.GITHUB else 'gitlab.com'-- issue_handler = issue_handler_factory(- issue_type, owner, repo, token, llm_config, platform, username, base_domain- )+ 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,+ )+ else: # platform == Platform.GITLAB+ return ServiceContextPR(+ GitlabPRHandler(+ self.owner,+ self.repo,+ self.token,+ self.username,+ self.base_domain,+ ),+ self.llm_config,+ )+ else:+ raise ValueError(f'Invalid issue type: {self.issue_type}')- # Load dataset- issues: list[Issue] = issue_handler.get_converted_issues(- issue_numbers=[issue_number], comment_id=comment_id- )+ async def resolve_issue(+ self,+ reset_logger: bool = False,+ ) -> None:+ """Resolve a single issue.- if not issues:- raise ValueError(- f'No issues found for issue number {issue_number}. Please verify that:\n'- f'1. The issue/PR #{issue_number} exists in the repository {owner}/{repo}\n'- f'2. You have the correct permissions to access it\n'- f'3. The repository name is spelled correctly'- )+ Args:+ reset_logger: Whether to reset the logger for multiprocessing.+ """- issue = issues[0]+ issue_handler = self.issue_handler_factory()- if comment_id is not None:- if (- issue_type == 'pr'- and not issue.review_comments- and not issue.review_threads- and not issue.thread_comments- ):- raise ValueError(- f'Comment ID {comment_id} did not have a match for issue {issue.number}'- )+ # Load dataset+ issues: list[Issue] = issue_handler.get_converted_issues(+ issue_numbers=[self.issue_number], comment_id=self.comment_id+ )- if issue_type == 'issue' and not issue.thread_comments:+ if not issues:raise ValueError(- f'Comment ID {comment_id} did not have a match for issue {issue.number}'+ 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')- # TEST METADATA- model_name = llm_config.model.split('/')[-1]+ issue = issues[0]++ 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}'+ )- pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)- pathlib.Path(os.path.join(output_dir, 'infer_logs')).mkdir(- parents=True, exist_ok=True- )- logger.info(f'Using output directory: {output_dir}')-- # checkout the repo- repo_dir = os.path.join(output_dir, 'repo')- if not os.path.exists(repo_dir):- checkout_output = subprocess.check_output( # noqa: ASYNC101- [- 'git',- 'clone',- issue_handler.get_clone_url(),- f'{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) # noqa: ASYNC101- .decode('utf-8')- .strip()- )- logger.info(f'Base commit: {base_commit}')+ 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}'+ )- if 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: # noqa: ASYNC101- repo_instruction = f.read()+ # TEST METADATA+ model_name = self.llm_config.model.split('/')[-1]- # OUTPUT FILE- output_file = os.path.join(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: # noqa: ASYNC101- for line in f:- data = ResolverOutput.model_validate_json(line)- if data.issue.number == issue_number:- logger.warning(- f'Issue {issue_number} was already processed. Skipping.'- )- return+ 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( # noqa: ASYNC101+ [+ 'git',+ 'clone',+ 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) # noqa: ASYNC101+ .decode('utf-8')+ .strip()+ )+ logger.info(f'Base commit: {base_commit}')- output_fp = open(output_file, 'a') # noqa: ASYNC101+ 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: # noqa: ASYNC101+ 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: # noqa: ASYNC101+ 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') # noqa: ASYNC101++ logger.info(+ f'Resolving issue {self.issue_number} with Agent {AGENT_CLASS}, model {model_name}, max iterations {self.max_iterations}.'+ )- logger.info(- f'Resolving issue {issue_number} with Agent {AGENT_CLASS}, model {model_name}, max iterations {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}'+ )- try:- # checkout to pr branch if needed- if 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')- 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( # noqa: ASYNC101+ fetch_cmd,+ cwd=repo_dir,+ )- # Fetch the branch first to ensure it exists locally- fetch_cmd = ['git', 'fetch', 'origin', branch_to_use]- subprocess.check_output( # noqa: ASYNC101- fetch_cmd,- cwd=repo_dir,- )+ # Checkout the branch+ checkout_cmd = ['git', 'checkout', branch_to_use]+ subprocess.check_output( # noqa: ASYNC101+ checkout_cmd,+ cwd=repo_dir,+ )- # Checkout the branch- checkout_cmd = ['git', 'checkout', branch_to_use]- subprocess.check_output( # noqa: ASYNC101- checkout_cmd,- cwd=repo_dir,- )+ base_commit = (+ subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir) # noqa: ASYNC101+ .decode('utf-8')+ .strip()+ )- base_commit = (- subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir) # noqa: ASYNC101- .decode('utf-8')- .strip()+ output = await self.process_issue(+ issue,+ base_commit,+ issue_handler,+ reset_logger,)+ output_fp.write(output.model_dump_json() + '\n')+ output_fp.flush()- output = await process_issue(- issue,- platform,- base_commit,- max_iterations,- llm_config,- output_dir,- base_container_image,- runtime_container_image,- prompt_template,- issue_handler,- repo_instruction,- reset_logger,- )- output_fp.write(output.model_dump_json() + '\n')- output_fp.flush()-- finally:- output_fp.close()- logger.info('Finished.')+ finally:+ output_fp.close()+ logger.info('Finished.')def main() -> None:@@ -660,99 +752,8 @@ def main() -> None:my_args = parser.parse_args()- base_container_image = my_args.base_container_image-- runtime_container_image = my_args.runtime_container_image-- 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 my_args.is_experimental- ):- runtime_container_image = (- f'ghcr.io/all-hands-ai/runtime:{openhands.__version__}-nikolaik'- )-- parts = my_args.selected_repo.rsplit('/', 1)- if len(parts) < 2:- raise ValueError('Invalid repository format. Expected owner/repo')- owner, repo = parts-- token = my_args.token or os.getenv('GITHUB_TOKEN') or os.getenv('GITLAB_TOKEN')- username = my_args.username if my_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,- my_args.base_domain,- )-- api_key = my_args.llm_api_key or os.environ['LLM_API_KEY']- model = my_args.llm_model or os.environ['LLM_MODEL']- base_url = my_args.llm_base_url or os.environ.get('LLM_BASE_URL', None)- api_version = os.environ.get('LLM_API_VERSION', None)-- # Create LLMConfig instance- llm_config = LLMConfig(- model=model,- api_key=SecretStr(api_key) if api_key else None,- base_url=base_url,- )-- # Only set api_version if it was explicitly provided, otherwise let LLMConfig handle it- if api_version is not None:- llm_config.api_version = api_version-- repo_instruction = None- if my_args.repo_instruction_file:- with open(my_args.repo_instruction_file, 'r') as f:- repo_instruction = f.read()-- issue_type = my_args.issue_type-- # Read the prompt template- prompt_file = my_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:- prompt_template = f.read()-- asyncio.run(- resolve_issue(- owner=owner,- repo=repo,- token=token,- username=username,- platform=platform,- base_container_image=base_container_image,- runtime_container_image=runtime_container_image,- max_iterations=my_args.max_iterations,- output_dir=my_args.output_dir,- llm_config=llm_config,- prompt_template=prompt_template,- issue_type=issue_type,- repo_instruction=repo_instruction,- issue_number=my_args.issue_number,- comment_id=my_args.comment_id,- base_domain=my_args.base_domain,- )- )+ issue_resolver = IssueResolver(my_args)+ asyncio.run(issue_resolver.resolve_issue())if __name__ == '__main__':diff --git a/tests/unit/resolver/github/test_resolve_issues.py b/tests/unit/resolver/github/test_resolve_issues.pyindex 01706ee1bd..00ebd13e6f 100644--- a/tests/unit/resolver/github/test_resolve_issues.py+++ b/tests/unit/resolver/github/test_resolve_issues.py@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom openhands.core.config import LLMConfig-from openhands.events.action import CmdRunAction+from openhands.events.action import CmdRunAction, MessageActionfrom openhands.events.observation import (CmdOutputMetadata,CmdOutputObservation,@@ -19,14 +19,47 @@ from openhands.resolver.interfaces.issue_definitions import (ServiceContextIssue,ServiceContextPR,)-from openhands.resolver.resolve_issue import (- complete_runtime,- initialize_runtime,- process_issue,-)+from openhands.resolver.resolve_issue import IssueResolverfrom 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.resolve_issue.identify_token', return_value=ProviderType.GITHUB) as patched:+ yield patched++@pytest.fixturedef mock_output_dir():with tempfile.TemporaryDirectory() as temp_dir:@@ -72,7 +105,7 @@ def create_cmd_output(exit_code: int, content: str, command: str):)-def test_initialize_runtime():+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'),@@ -81,7 +114,10 @@ def test_initialize_runtime():),]- initialize_runtime(mock_runtime, ProviderType.GITHUB)+ # Create resolver with mocked token identification+ resolver = IssueResolver(default_mock_args)++ resolver.initialize_runtime(mock_runtime)assert mock_runtime.run_action.call_count == 2mock_runtime.run_action.assert_any_call(CmdRunAction(command='cd /workspace'))@@ -91,40 +127,32 @@ def test_initialize_runtime():@pytest.mark.asyncio-async def test_resolve_issue_no_issues_found():- from openhands.resolver.resolve_issue import resolve_issue-+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 dependenciesmock_handler = MagicMock()mock_handler.get_converted_issues.return_value = [] # Return empty list- with patch(- 'openhands.resolver.resolve_issue.issue_handler_factory',- return_value=mock_handler,- ):- with pytest.raises(ValueError) as exc_info:- await resolve_issue(- owner='test-owner',- repo='test-repo',- token='test-token',- username='test-user',- platform=ProviderType.GITHUB,- max_iterations=5,- output_dir='/tmp',- llm_config=LLMConfig(model='test', api_key='test'),- base_container_image='test-image',- runtime_container_image='test-image',- prompt_template='test-template',- issue_type='pr',- repo_instruction=None,- issue_number=5432,- comment_id=None,- )+ # 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_factory method+ resolver.issue_handler_factory = MagicMock(return_value=mock_handler)++ # Test that the correct exception is raised+ with pytest.raises(ValueError) as exc_info:+ await resolver.resolve_issue()- assert 'No issues found for issue number 5432' in str(exc_info.value)- assert 'test-owner/test-repo' in str(exc_info.value)- assert 'exists in the repository' in str(exc_info.value)- assert 'correct permissions' in str(exc_info.value)+ # 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)++ # Verify that the handler was correctly configured and called+ resolver.issue_handler_factory.assert_called_once()+ mock_handler.get_converted_issues.assert_called_once_with(issue_numbers=[5432], comment_id=None)def test_download_issues_from_github():@@ -298,7 +326,8 @@ def test_download_pr_from_github():@pytest.mark.asyncio-async def test_complete_runtime():+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'),@@ -316,8 +345,11 @@ async def test_complete_runtime():create_cmd_output(exit_code=0, content='git diff content', command='git apply'),]- result = await complete_runtime(- mock_runtime, 'base_commit_hash', ProviderType.GITHUB+ # 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'}@@ -325,31 +357,9 @@ async def test_complete_runtime():@pytest.mark.asyncio-async def test_process_issue(mock_output_dir, mock_prompt_template):- # Mock dependencies- mock_create_runtime = MagicMock()- mock_initialize_runtime = AsyncMock()- mock_run_controller = AsyncMock()- mock_complete_runtime = AsyncMock()- handler_instance = MagicMock()-- # 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'- repo_instruction = 'Resolve this repo'- max_iterations = 5- llm_config = LLMConfig(model='test_model', api_key='test_api_key')- base_container_image = 'test_image:latest'- runtime_container_image = 'test_image:latest'-- # Test cases for different scenarios- test_cases = [+ "test_case",+ [{'name': 'successful_run','run_controller_return': MagicMock(@@ -363,6 +373,8 @@ async def test_process_issue(mock_output_dir, mock_prompt_template):'expected_success': True,'expected_error': None,'expected_explanation': 'Issue resolved successfully',+ 'is_pr': False,+ 'comment_success': None,},{'name': 'value_error',@@ -371,6 +383,8 @@ async def test_process_issue(mock_output_dir, mock_prompt_template):'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',@@ -379,6 +393,8 @@ async def test_process_issue(mock_output_dir, mock_prompt_template):'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',@@ -394,93 +410,101 @@ async def test_process_issue(mock_output_dir, mock_prompt_template):'expected_error': None,'expected_explanation': 'Non-JSON explanation','is_pr': True,- 'comment_success': [- True,- False,- ], # To trigger the PR success logging code path+ '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_prompt_template, test_case):+ """Test the process_issue method with different scenarios."""- for test_case in test_cases:- # Reset mocks- mock_create_runtime.reset_mock()- mock_initialize_runtime.reset_mock()- mock_run_controller.reset_mock()- mock_complete_runtime.reset_mock()- handler_instance.reset_mock()-- # Mock return values- mock_create_runtime.return_value = MagicMock(connect=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']- mock_run_controller.side_effect = None-- mock_complete_runtime.return_value = {'git_patch': 'test patch'}- 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', [])- handler_instance.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'+ # 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'- with (- patch(- 'openhands.resolver.resolve_issue.create_runtime', mock_create_runtime- ),- patch(- 'openhands.resolver.resolve_issue.initialize_runtime',- mock_initialize_runtime,- ),- patch(- 'openhands.resolver.resolve_issue.run_controller', mock_run_controller- ),- patch(- 'openhands.resolver.resolve_issue.complete_runtime',- mock_complete_runtime,- ),- patch('openhands.resolver.resolve_issue.logger'),- ):- # Call the function- result = await process_issue(- issue,- ProviderType.GITHUB,- base_commit,- max_iterations,- llm_config,- mock_output_dir,- base_container_image,- runtime_container_image,- mock_prompt_template,- handler_instance,- repo_instruction,- reset_logger=False,- )+ # Create a resolver instance with mocked token identification+ resolver = IssueResolver(default_mock_args)+ resolver.prompt_template = mock_prompt_template- # Assert the result- expected_issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'- assert handler_instance.issue_type == expected_issue_type- 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_initialize_runtime.assert_called_once()- mock_run_controller.assert_called_once()- mock_complete_runtime.assert_called_once()-- # 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()+ # Mock the handler+ 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', [])+ handler_instance.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'++ # 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.resolve_issue.create_runtime', mock_create_runtime), \+ patch('openhands.resolver.resolve_issue.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_prompt_template, mock_followup_prompt_template):diff --git a/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py b/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.pyindex ff9b061074..17661c09f1 100644--- a/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py+++ b/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py@@ -19,14 +19,46 @@ from openhands.resolver.interfaces.issue_definitions import (ServiceContextIssue,ServiceContextPR,)-from openhands.resolver.resolve_issue import (- complete_runtime,- initialize_runtime,- process_issue,-)+from openhands.resolver.resolve_issue import IssueResolver, SandboxConfig, AppConfig, AgentConfigfrom 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.resolve_issue.identify_token', return_value=ProviderType.GITLAB) as patched:+ yield patched++@pytest.fixturedef mock_output_dir():with tempfile.TemporaryDirectory() as temp_dir:@@ -72,7 +104,7 @@ def create_cmd_output(exit_code: int, content: str, command: str):)-def test_initialize_runtime():+def test_initialize_runtime(default_mock_args, mock_gitlab_token):mock_runtime = MagicMock()if os.getenv('GITLAB_CI') == 'true':@@ -92,8 +124,11 @@ def test_initialize_runtime():exit_code=0, content='', command='git config --global core.pager ""'),]-- initialize_runtime(mock_runtime, ProviderType.GITLAB)++ # 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@@ -111,40 +146,32 @@ def test_initialize_runtime():@pytest.mark.asyncio-async def test_resolve_issue_no_issues_found():- from openhands.resolver.resolve_issue import resolve_issue-+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 dependenciesmock_handler = MagicMock()mock_handler.get_converted_issues.return_value = [] # Return empty list- with patch(- 'openhands.resolver.resolve_issue.issue_handler_factory',- return_value=mock_handler,- ):- with pytest.raises(ValueError) as exc_info:- await resolve_issue(- owner='test-owner',- repo='test-repo',- token='test-token',- username='test-user',- platform=ProviderType.GITLAB,- max_iterations=5,- output_dir='/tmp',- llm_config=LLMConfig(model='test', api_key='test'),- base_container_image='test-image',- runtime_container_image='test-image',- prompt_template='test-template',- issue_type='pr',- repo_instruction=None,- issue_number=5432,- comment_id=None,- )-- assert 'No issues found for issue number 5432' in str(exc_info.value)- assert 'test-owner/test-repo' in str(exc_info.value)- assert 'exists in the repository' in str(exc_info.value)- assert 'correct permissions' in str(exc_info.value)+ # 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_factory method+ resolver.issue_handler_factory = MagicMock(return_value=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)++ # Verify that the handler was correctly configured and called+ resolver.issue_handler_factory.assert_called_once()+ mock_handler.get_converted_issues.assert_called_once_with(issue_numbers=[5432], comment_id=None)def test_download_issues_from_gitlab():@@ -338,7 +365,7 @@ def test_download_pr_from_gitlab():@pytest.mark.asyncio-async def test_complete_runtime():+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'),@@ -351,45 +378,24 @@ async def test_complete_runtime():command='git config --global --add safe.directory /workspace',),create_cmd_output(- exit_code=0, content='', command='git diff base_commit_hash fix'+ exit_code=0, content='', command='git add -A'),- create_cmd_output(exit_code=0, content='git diff content', command='git apply'),+ 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 complete_runtime(- mock_runtime, 'base_commit_hash', ProviderType.GITLAB- )+ 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@pytest.mark.asyncio-async def test_process_issue(mock_output_dir, mock_prompt_template):- # Mock dependencies- mock_create_runtime = MagicMock()- mock_initialize_runtime = AsyncMock()- mock_run_controller = AsyncMock()- mock_complete_runtime = AsyncMock()- handler_instance = MagicMock()-- # 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'- repo_instruction = 'Resolve this repo'- max_iterations = 5- llm_config = LLMConfig(model='test_model', api_key='test_api_key')- base_container_image = 'test_image:latest'- runtime_container_image = 'test_image:latest'-- # Test cases for different scenarios- test_cases = [+ "test_case",+ [{'name': 'successful_run','run_controller_return': MagicMock(@@ -403,22 +409,26 @@ async def test_process_issue(mock_output_dir, mock_prompt_template):'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',@@ -434,94 +444,82 @@ async def test_process_issue(mock_output_dir, mock_prompt_template):'expected_error': None,'expected_explanation': 'Non-JSON explanation','is_pr': True,- 'comment_success': [- True,- False,- ], # To trigger the PR success logging code path+ 'comment_success': [True, False],},- ]+ ],+)+async def test_process_issue(default_mock_args, mock_gitlab_token, mock_output_dir, mock_prompt_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'- for test_case in test_cases:- # Reset mocks- mock_create_runtime.reset_mock()- mock_initialize_runtime.reset_mock()- mock_run_controller.reset_mock()- mock_complete_runtime.reset_mock()- handler_instance.reset_mock()-- # Mock return values- mock_create_runtime.return_value = MagicMock(connect=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']- mock_run_controller.side_effect = None-- mock_complete_runtime.return_value = {'git_patch': 'test patch'}- 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', [])- handler_instance.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'+ # 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'- with (- patch(- 'openhands.resolver.resolve_issue.create_runtime', mock_create_runtime- ),- patch(- 'openhands.resolver.resolve_issue.initialize_runtime',- mock_initialize_runtime,- ),- patch(- 'openhands.resolver.resolve_issue.run_controller', mock_run_controller- ),- patch(- 'openhands.resolver.resolve_issue.complete_runtime',- mock_complete_runtime,- ),- patch('openhands.resolver.resolve_issue.logger'),- ):- # Call the function- result = await process_issue(- issue,- ProviderType.GITLAB,- base_commit,- max_iterations,- llm_config,- mock_output_dir,- base_container_image,- runtime_container_image,- mock_prompt_template,- handler_instance,- repo_instruction,- reset_logger=False,- )+ # Create a resolver instance with mocked token identification+ resolver = IssueResolver(default_mock_args)+ resolver.prompt_template = mock_prompt_template- # Assert the result- expected_issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'- assert handler_instance.issue_type == expected_issue_type- 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_initialize_runtime.assert_called_once()- mock_run_controller.assert_called_once()- mock_complete_runtime.assert_called_once()-- # 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()+ # Mock the handler+ 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', [])+ handler_instance.issue_type = 'pr' if test_case.get('is_pr', False) else 'issue'+ # 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.resolve_issue.create_runtime', mock_create_runtime), \+ patch('openhands.resolver.resolve_issue.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.resolve_issue.SandboxConfig', return_value=MagicMock()), \+ patch('openhands.resolver.resolve_issue.AppConfig', 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_prompt_template, mock_followup_prompt_template):issue = Issue(@@ -925,4 +923,4 @@ def test_download_issue_with_specific_comment():if __name__ == '__main__':- pytest.main()+ pytest.main()\ No newline at end of file