π OpenHands: AI-Driven Development
Add GitLab alternative directory support for microagents (#9331)
Graham Neubig0e4aeba47c35
diff --git a/docs/usage/prompting/microagents-org.mdx b/docs/usage/prompting/microagents-org.mdxindex 3444abb9f5..40ce77e0d8 100644--- a/docs/usage/prompting/microagents-org.mdx+++ b/docs/usage/prompting/microagents-org.mdx@@ -11,6 +11,8 @@ accordingly. However, they are applied to all repositories belonging to the orgaAdd a `.openhands` repository under the organization or user and create a `microagents` directory and place themicroagents in that directory.+For GitLab organizations, use `openhands-config` as the repository name instead of `.openhands`, since GitLab doesn't support repository names starting with non-alphanumeric characters.+## ExampleGeneral microagent file example for organization `Great-Co` located inside the `.openhands` repository:@@ -20,3 +22,5 @@ General microagent file example for organization `Great-Co` located inside the `* Document interfaces and public APIs; use implementation comments only for non-obvious logic.* Follow the same naming convention for variables, classes, constants, etc. already used in each repository.```++For GitLab organizations, the same microagent would be located inside the `openhands-config` repository.diff --git a/openhands/runtime/base.py b/openhands/runtime/base.pyindex 1e4e5ebe73..53b6aaff90 100644--- a/openhands/runtime/base.py+++ b/openhands/runtime/base.py@@ -653,15 +653,43 @@ fireturn remote_url+ def _is_gitlab_repository(self, repo_name: str) -> bool:+ """Check if a repository is hosted on GitLab.++ Args:+ repo_name: Repository name (e.g., "gitlab.com/org/repo" or "org/repo")++ Returns:+ True if the repository is hosted on GitLab, False otherwise+ """+ try:+ provider_handler = ProviderHandler(+ self.git_provider_tokens or MappingProxyType({})+ )+ repository = call_async_from_sync(+ provider_handler.verify_repo_provider,+ GENERAL_TIMEOUT,+ repo_name,+ )+ return repository.git_provider == ProviderType.GITLAB+ except Exception:+ # If we can't determine the provider, assume it's not GitLab+ # This is a safe fallback since we'll just use the default .openhands+ return False+def get_microagents_from_org_or_user(self, selected_repository: str) -> list[BaseMicroagent]:- """Load microagents from the organization or user level .openhands repository.+ """Load microagents from the organization or user level repository.For example, if the repository is github.com/acme-co/api, this will check ifgithub.com/acme-co/.openhands exists. If it does, it will clone it and loadthe microagents from the ./microagents/ folder.+ For GitLab repositories, it will use openhands-config instead of .openhands+ since GitLab doesn't support repository names starting with non-alphanumeric+ characters.+Args:selected_repository: The repository path (e.g., "github.com/acme-co/api")@@ -677,15 +705,22 @@ fi# Extract the domain and org/user nameorg_name = repo_parts[-2]- # Construct the org-level .openhands repo path- org_openhands_repo = f'{org_name}/.openhands'+ # Determine if this is a GitLab repository+ is_gitlab = self._is_gitlab_repository(selected_repository)++ # For GitLab, use openhands-config (since .openhands is not a valid repo name)+ # For other providers, use .openhands+ if is_gitlab:+ org_openhands_repo = f'{org_name}/openhands-config'+ else:+ org_openhands_repo = f'{org_name}/.openhands'self.log('info',f'Checking for org-level microagents at {org_openhands_repo}',)- # Try to clone the org-level .openhands repo+ # Try to clone the org-level repotry:# Create a temporary directory for the org-level repoorg_repo_dir = self.workspace_root / f'org_openhands_{org_name}'@@ -729,7 +764,10 @@ fi)except Exception as e:- self.log('error', f'Error loading org-level microagents: {str(e)}')+ self.log(+ 'debug',+ f'Error loading org-level microagents from {org_openhands_repo}: {str(e)}',+ )return loaded_microagents@@ -740,9 +778,13 @@ fiIf selected_repository is None, load microagents from the current workspace.This is the main entry point for loading microagents.- This method also checks for user/org level microagents stored in a .openhands repository.+ This method also checks for user/org level microagents stored in a repository.For example, if the repository is github.com/acme-co/api, it will also check forgithub.com/acme-co/.openhands and load microagents from there if it exists.++ For GitLab repositories, it will use openhands-config instead of .openhands+ since GitLab doesn't support repository names starting with non-alphanumeric+ characters."""loaded_microagents: list[BaseMicroagent] = []microagents_dir = self.workspace_root / '.openhands' / 'microagents'diff --git a/tests/unit/test_runtime_gitlab_microagents.py b/tests/unit/test_runtime_gitlab_microagents.pynew file mode 100644index 0000000000..39172333c9--- /dev/null+++ b/tests/unit/test_runtime_gitlab_microagents.py@@ -0,0 +1,310 @@+"""Tests for GitLab alternative directory support for microagents."""++import tempfile+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++from openhands.integrations.service_types import ProviderType, Repository+from openhands.microagent.microagent import (+ RepoMicroagent,+)+from openhands.runtime.base import Runtime+++class MockRuntime(Runtime):+ """Mock runtime for testing."""++ def __init__(self, workspace_root: Path):+ self._workspace_root = workspace_root+ self.git_provider_tokens = {}+ self._logs = []++ @property+ def workspace_root(self) -> Path:+ """Return the workspace root path."""+ return self._workspace_root++ def log(self, level: str, message: str):+ """Mock log method."""+ self._logs.append((level, message))++ def run_action(self, action):+ """Mock run_action method."""+ # For testing, we'll simulate successful cloning+ from openhands.events.observation import CmdOutputObservation++ return CmdOutputObservation(content='', exit_code=0)++ def read(self, action):+ """Mock read method."""+ from openhands.events.observation import ErrorObservation++ return ErrorObservation('File not found')++ def _load_microagents_from_directory(self, directory: Path, source: str):+ """Mock microagent loading."""+ if not directory.exists():+ return []++ # Create mock microagents based on directory structure+ microagents = []+ for md_file in directory.rglob('*.md'):+ if md_file.name == 'README.md':+ continue++ # Create a simple mock microagent+ from openhands.microagent.types import MicroagentMetadata, MicroagentType++ agent = RepoMicroagent(+ name=f'mock_{md_file.stem}',+ content=f'Mock content from {md_file}',+ metadata=MicroagentMetadata(name=f'mock_{md_file.stem}'),+ source=str(md_file),+ type=MicroagentType.REPO_KNOWLEDGE,+ )+ microagents.append(agent)++ return microagents++ # Implement abstract methods with minimal functionality+ def connect(self):+ pass++ def run(self, action):+ from openhands.events.observation import CmdOutputObservation++ return CmdOutputObservation(content='', exit_code=0)++ def run_ipython(self, action):+ from openhands.events.observation import IPythonRunCellObservation++ return IPythonRunCellObservation(content='', code='')++ def edit(self, action):+ from openhands.events.observation import FileEditObservation++ return FileEditObservation(content='', path='')++ def browse(self, action):+ from openhands.events.observation import BrowserObservation++ return BrowserObservation(content='', url='', screenshot='')++ def browse_interactive(self, action):+ from openhands.events.observation import BrowserObservation++ return BrowserObservation(content='', url='', screenshot='')++ def write(self, action):+ from openhands.events.observation import FileWriteObservation++ return FileWriteObservation(content='', path='')++ def copy_to(self, host_src, sandbox_dest, recursive=False):+ pass++ def copy_from(self, sandbox_src, host_dest, recursive=False):+ pass++ def list_files(self, path=None):+ return []++ def get_mcp_config(self, extra_stdio_servers=None):+ from openhands.core.config.mcp_config import MCPConfig++ return MCPConfig()++ def call_tool_mcp(self, action):+ from openhands.events.observation import MCPObservation++ return MCPObservation(content='', tool='', result='')+++def create_test_microagents(base_dir: Path, config_dir_name: str = '.openhands'):+ """Create test microagent files in the specified directory."""+ microagents_dir = base_dir / config_dir_name / 'microagents'+ microagents_dir.mkdir(parents=True, exist_ok=True)++ # Create a test microagent+ test_agent = """---+name: test_agent+type: repo+version: 1.0.0+agent: CodeActAgent+---++# Test Agent++This is a test microagent.+"""+ (microagents_dir / 'test.md').write_text(test_agent)+ return microagents_dir+++def temp_workspace():+ """Create a temporary workspace directory."""+ with tempfile.TemporaryDirectory() as temp_dir:+ yield Path(temp_dir)+++def test_is_gitlab_repository_github(temp_workspace):+ """Test that GitHub repositories are correctly identified as non-GitLab."""+ runtime = MockRuntime(temp_workspace)++ # Mock the provider handler to return GitHub+ mock_repo = Repository(+ id='123',+ full_name='owner/repo',+ git_provider=ProviderType.GITHUB,+ is_public=True,+ )++ with patch('openhands.runtime.base.ProviderHandler') as mock_handler_class:+ mock_handler = MagicMock()+ mock_handler_class.return_value = mock_handler++ with patch('openhands.runtime.base.call_async_from_sync') as mock_async:+ mock_async.return_value = mock_repo++ result = runtime._is_gitlab_repository('github.com/owner/repo')+ assert result is False+++def test_is_gitlab_repository_gitlab(temp_workspace):+ """Test that GitLab repositories are correctly identified."""+ runtime = MockRuntime(temp_workspace)++ # Mock the provider handler to return GitLab+ mock_repo = Repository(+ id='456',+ full_name='owner/repo',+ git_provider=ProviderType.GITLAB,+ is_public=True,+ )++ with patch('openhands.runtime.base.ProviderHandler') as mock_handler_class:+ mock_handler = MagicMock()+ mock_handler_class.return_value = mock_handler++ with patch('openhands.runtime.base.call_async_from_sync') as mock_async:+ mock_async.return_value = mock_repo++ result = runtime._is_gitlab_repository('gitlab.com/owner/repo')+ assert result is True+++def test_is_gitlab_repository_exception(temp_workspace):+ """Test that exceptions in provider detection return False."""+ runtime = MockRuntime(temp_workspace)++ with patch('openhands.runtime.base.ProviderHandler') as mock_handler_class:+ mock_handler_class.side_effect = Exception('Provider error')++ result = runtime._is_gitlab_repository('unknown.com/owner/repo')+ assert result is False+++def test_get_microagents_from_org_or_user_github(temp_workspace):+ """Test that GitHub repositories only try .openhands directory."""+ runtime = MockRuntime(temp_workspace)++ # Mock the provider detection to return GitHub+ with patch.object(runtime, '_is_gitlab_repository', return_value=False):+ # Mock the _get_authenticated_git_url to simulate failure (no org repo)+ with patch('openhands.runtime.base.call_async_from_sync') as mock_async:+ mock_async.side_effect = Exception('Repository not found')++ result = runtime.get_microagents_from_org_or_user('github.com/owner/repo')++ # Should only try .openhands, not openhands-config+ assert len(result) == 0+ # Check that only one attempt was made (for .openhands)+ assert mock_async.call_count == 1+++def test_get_microagents_from_org_or_user_gitlab_success_with_config(temp_workspace):+ """Test that GitLab repositories use openhands-config and succeed."""+ runtime = MockRuntime(temp_workspace)++ # Create a mock org directory with microagents+ org_dir = temp_workspace / 'org_openhands_owner'+ create_test_microagents(org_dir, '.') # Create microagents directly in org_dir++ # Mock the provider detection to return GitLab+ with patch.object(runtime, '_is_gitlab_repository', return_value=True):+ # Mock successful cloning for openhands-config+ with patch('openhands.runtime.base.call_async_from_sync') as mock_async:+ mock_async.return_value = 'https://gitlab.com/owner/openhands-config.git'++ result = runtime.get_microagents_from_org_or_user('gitlab.com/owner/repo')++ # Should succeed with openhands-config+ assert len(result) >= 0 # May be empty if no microagents found+ # Should only try once for openhands-config+ assert mock_async.call_count == 1+++def test_get_microagents_from_org_or_user_gitlab_failure(temp_workspace):+ """Test that GitLab repositories handle failure gracefully when openhands-config doesn't exist."""+ runtime = MockRuntime(temp_workspace)++ # Mock the provider detection to return GitLab+ with patch.object(runtime, '_is_gitlab_repository', return_value=True):+ # Mock the _get_authenticated_git_url to fail for openhands-config+ with patch('openhands.runtime.base.call_async_from_sync') as mock_async:+ mock_async.side_effect = Exception('openhands-config not found')++ result = runtime.get_microagents_from_org_or_user('gitlab.com/owner/repo')++ # Should return empty list when repository doesn't exist+ assert len(result) == 0+ # Should only try once for openhands-config+ assert mock_async.call_count == 1+++def test_get_microagents_from_selected_repo_gitlab_uses_openhands(temp_workspace):+ """Test that GitLab repositories use .openhands directory for repository-specific microagents."""+ runtime = MockRuntime(temp_workspace)++ # Create a repository directory structure+ repo_dir = temp_workspace / 'repo'+ repo_dir.mkdir()++ # Create microagents in .openhands directory+ create_test_microagents(repo_dir, '.openhands')++ # Mock the provider detection to return GitLab+ with patch.object(runtime, '_is_gitlab_repository', return_value=True):+ # Mock org-level microagents (empty)+ with patch.object(runtime, 'get_microagents_from_org_or_user', return_value=[]):+ result = runtime.get_microagents_from_selected_repo('gitlab.com/owner/repo')++ # Should find microagents from .openhands directory+ # The exact assertion depends on the mock implementation+ # At minimum, it should not raise an exception+ assert isinstance(result, list)+++def test_get_microagents_from_selected_repo_github_only_openhands(temp_workspace):+ """Test that GitHub repositories only check .openhands directory."""+ runtime = MockRuntime(temp_workspace)++ # Create a repository directory structure+ repo_dir = temp_workspace / 'repo'+ repo_dir.mkdir()++ # Create microagents in both directories+ create_test_microagents(repo_dir, 'openhands-config')+ create_test_microagents(repo_dir, '.openhands')++ # Mock the provider detection to return GitHub+ with patch.object(runtime, '_is_gitlab_repository', return_value=False):+ # Mock org-level microagents (empty)+ with patch.object(runtime, 'get_microagents_from_org_or_user', return_value=[]):+ result = runtime.get_microagents_from_selected_repo('github.com/owner/repo')++ # Should only check .openhands directory, not openhands-config+ assert isinstance(result, list)