π OpenHands: AI-Driven Development
fix: use project_dir consistently for workspace.working_dir, setup.sh, and git hooks (#13329)
Xingyao Wang53bb82fe2e47
diff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.pyindex 757c40de5d..54fc7c16b3 100644--- a/openhands/app_server/app_conversation/app_conversation_router.py+++ b/openhands/app_server/app_conversation/app_conversation_router.py@@ -49,6 +49,7 @@ from openhands.app_server.app_conversation.app_conversation_service import ()from openhands.app_server.app_conversation.app_conversation_service_base import (AppConversationServiceBase,+ get_project_dir,)from openhands.app_server.app_conversation.app_conversation_start_task_service import (AppConversationStartTaskService,@@ -540,10 +541,13 @@ async def get_conversation_skills(# Prefer the shared loader to avoid duplication; otherwise return empty list.all_skills: list = []if isinstance(app_conversation_service, AppConversationServiceBase):+ project_dir = get_project_dir(+ sandbox_spec.working_dir, conversation.selected_repository+ )all_skills = await app_conversation_service.load_and_merge_all_skills(sandbox,conversation.selected_repository,- sandbox_spec.working_dir,+ project_dir,agent_server_url,)diff --git a/openhands/app_server/app_conversation/app_conversation_service_base.py b/openhands/app_server/app_conversation/app_conversation_service_base.pyindex 86cab99fae..52cdf660d1 100644--- a/openhands/app_server/app_conversation/app_conversation_service_base.py+++ b/openhands/app_server/app_conversation/app_conversation_service_base.py@@ -47,6 +47,40 @@ PRE_COMMIT_HOOK = '.git/hooks/pre-commit'PRE_COMMIT_LOCAL = '.git/hooks/pre-commit.local'+def get_project_dir(+ working_dir: str,+ selected_repository: str | None = None,+) -> str:+ """Get the project root directory for a conversation.++ When a repository is selected, the project root is the cloned repo directory+ at {working_dir}/{repo_name}. This is the directory that contains the+ `.openhands/` configuration (setup.sh, pre-commit.sh, skills/, etc.).++ Without a repository, the project root is the working_dir itself.++ This must be used consistently for ALL features that depend on the project root:+ - workspace.working_dir (terminal CWD, file editor root, etc.)+ - .openhands/setup.sh execution+ - .openhands/pre-commit.sh (git hooks setup)+ - .openhands/skills/ (project skills)+ - PLAN.md path++ Args:+ working_dir: Base working directory path in the sandbox+ (e.g., '/workspace/project' from sandbox_spec)+ selected_repository: Repository name (e.g., 'OpenHands/software-agent-sdk')+ If provided, the repo name is appended to working_dir.++ Returns:+ The project root directory path.+ """+ if selected_repository:+ repo_name = selected_repository.split('/')[-1]+ return f'{working_dir}/{repo_name}'+ return working_dir++@dataclassclass AppConversationServiceBase(AppConversationService, ABC):"""App Conversation service which adds git specific functionality.@@ -61,7 +95,7 @@ class AppConversationServiceBase(AppConversationService, ABC):self,sandbox: SandboxInfo,selected_repository: str | None,- working_dir: str,+ project_dir: str,agent_server_url: str,) -> list[Skill]:"""Load skills from all sources via the agent-server.@@ -77,7 +111,7 @@ class AppConversationServiceBase(AppConversationService, ABC):Args:sandbox: SandboxInfo containing exposed URLs and agent-server URLselected_repository: Repository name or None- working_dir: Working directory path+ project_dir: Project root directory (resolved via get_project_dir).agent_server_url: Agent-server URL (required)Returns:@@ -96,12 +130,6 @@ class AppConversationServiceBase(AppConversationService, ABC):# Build sandbox config (exposed URLs)sandbox_config = build_sandbox_config(sandbox)- # Determine project directory for project skills- project_dir = working_dir- if selected_repository:- repo_name = selected_repository.split('/')[-1]- project_dir = f'{working_dir}/{repo_name}'-# Single API call to agent-server for ALL skillsall_skills = await load_skills_from_agent_server(agent_server_url=agent_server_url,@@ -180,24 +208,25 @@ class AppConversationServiceBase(AppConversationService, ABC):agent: Agent,remote_workspace: AsyncRemoteWorkspace,selected_repository: str | None,- working_dir: str,+ project_dir: str,):"""Load all skills and update agent with them.Args:agent: The agent to updateremote_workspace: AsyncRemoteWorkspace for loading repo skills- selected_repository: Repository name or None- working_dir: Working directory path+ selected_repository: Repository name or None (used for org config)+ project_dir: Project root directory (already resolved via get_project_dir).Returns:Updated agent with skills loaded into context"""- # Load and merge all skills- # Extract agent_server_url from remote_workspace hostagent_server_url = remote_workspace.hostall_skills = await self.load_and_merge_all_skills(- sandbox, selected_repository, working_dir, agent_server_url+ sandbox,+ selected_repository,+ project_dir,+ agent_server_url,)# Update agent with skills@@ -216,20 +245,27 @@ class AppConversationServiceBase(AppConversationService, ABC):yield taskawait self.clone_or_init_git_repo(task, workspace)+ # Compute the project root β the cloned repo directory when a repo is+ # selected, or the sandbox working_dir otherwise. This must be used+ # for all .openhands/ features (setup.sh, pre-commit.sh, skills).+ project_dir = get_project_dir(+ workspace.working_dir, task.request.selected_repository+ )+task.status = AppConversationStartTaskStatus.RUNNING_SETUP_SCRIPTyield task- await self.maybe_run_setup_script(workspace)+ await self.maybe_run_setup_script(workspace, project_dir)task.status = AppConversationStartTaskStatus.SETTING_UP_GIT_HOOKSyield task- await self.maybe_setup_git_hooks(workspace)+ await self.maybe_setup_git_hooks(workspace, project_dir)task.status = AppConversationStartTaskStatus.SETTING_UP_SKILLSyield taskawait self.load_and_merge_all_skills(sandbox,task.request.selected_repository,- workspace.working_dir,+ project_dir,agent_server_url,)@@ -334,26 +370,35 @@ class AppConversationServiceBase(AppConversationService, ABC):async def maybe_run_setup_script(self,workspace: AsyncRemoteWorkspace,+ project_dir: str,):- """Run .openhands/setup.sh if it exists in the workspace or repository."""- setup_script = workspace.working_dir + '/.openhands/setup.sh'+ """Run .openhands/setup.sh if it exists in the project root.++ Args:+ workspace: Remote workspace for command execution.+ project_dir: Project root directory (repo root when a repo is selected).+ """+ setup_script = project_dir + '/.openhands/setup.sh'await workspace.execute_command(- f'chmod +x {setup_script} && source {setup_script}', timeout=600+ f'chmod +x {setup_script} && source {setup_script}',+ cwd=project_dir,+ timeout=600,)- # TODO: Does this need to be done?- # Add the action to the event stream as an ENVIRONMENT event- # source = EventSource.ENVIRONMENT- # self.event_stream.add_event(action, source)-async def maybe_setup_git_hooks(self,workspace: AsyncRemoteWorkspace,+ project_dir: str,):- """Set up git hooks if .openhands/pre-commit.sh exists in the workspace or repository."""+ """Set up git hooks if .openhands/pre-commit.sh exists in the project root.++ Args:+ workspace: Remote workspace for command execution.+ project_dir: Project root directory (repo root when a repo is selected).+ """command = 'mkdir -p .git/hooks && chmod +x .openhands/pre-commit.sh'- result = await workspace.execute_command(command, workspace.working_dir)+ result = await workspace.execute_command(command, project_dir)if result.exit_code:return@@ -369,9 +414,7 @@ class AppConversationServiceBase(AppConversationService, ABC):f'mv {PRE_COMMIT_HOOK} {PRE_COMMIT_LOCAL} &&'f'chmod +x {PRE_COMMIT_LOCAL}')- result = await workspace.execute_command(- command, workspace.working_dir- )+ result = await workspace.execute_command(command, project_dir)if result.exit_code != 0:_logger.error(f'Failed to preserve existing pre-commit hook: {result.stderr}',diff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.pyindex b4ca372c16..97b92c6aa5 100644--- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py+++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py@@ -41,6 +41,7 @@ from openhands.app_server.app_conversation.app_conversation_service import ()from openhands.app_server.app_conversation.app_conversation_service_base import (AppConversationServiceBase,+ get_project_dir,)from openhands.app_server.app_conversation.app_conversation_start_task_service import (AppConversationStartTaskService,@@ -1227,7 +1228,12 @@ class LiveStatusAppConversationService(AppConversationServiceBase):5. Passing plugins to the agent server for remote plugin loading"""user = await self.user_context.get_user_info()- workspace = LocalWorkspace(working_dir=working_dir)++ # Compute the project root β this is the repo directory when a repo is+ # selected, or the sandbox working_dir otherwise. All tools, hooks,+ # setup scripts, and plan paths must use this consistently.+ project_dir = get_project_dir(working_dir, selected_repository)+ workspace = LocalWorkspace(working_dir=project_dir)# Set up secrets for all git providerssecrets = await self._setup_secrets_for_git_providers(user)@@ -1244,7 +1250,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):user.condenser_max_size,secrets=secrets,git_provider=git_provider,- working_dir=working_dir,+ working_dir=project_dir,)# Finalize and return the conversation request@@ -1258,7 +1264,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):sandbox,remote_workspace,selected_repository,- working_dir,+ project_dir,plugins=plugins,)diff --git a/tests/unit/app_server/test_app_conversation_service_base.py b/tests/unit/app_server/test_app_conversation_service_base.pyindex 701a59198a..f1d0711416 100644--- a/tests/unit/app_server/test_app_conversation_service_base.py+++ b/tests/unit/app_server/test_app_conversation_service_base.py@@ -1035,7 +1035,7 @@ class TestLoadAndMergeAllSkills:# Actresult = await service.load_and_merge_all_skills(- sandbox, 'owner/repo', '/workspace', 'http://localhost:8000'+ sandbox, 'owner/repo', '/workspace/repo', 'http://localhost:8000')# Assert@@ -1073,7 +1073,7 @@ class TestLoadAndMergeAllSkills:# Act - pass empty string to simulate no agent server URL# This should still call load_skills_from_agent_server but it will failresult = await service.load_and_merge_all_skills(- sandbox, 'owner/repo', '/workspace', ''+ sandbox, 'owner/repo', '/workspace/repo', '')# Assert - should return empty list when agent_server_url is empty@@ -1089,13 +1089,13 @@ class TestLoadAndMergeAllSkills:@patch('openhands.app_server.app_conversation.app_conversation_service_base.build_sandbox_config')- async def test_uses_working_dir_when_no_repository(+ async def test_uses_project_dir_when_no_repository(self,mock_build_sandbox_config,mock_build_org_config,mock_load_skills,):- """Test uses working_dir as project_dir when no repository is selected."""+ """Test uses project_dir directly when no repository is selected."""# Arrangemock_user_context = Mock(spec=UserContext)with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):@@ -1164,7 +1164,7 @@ class TestLoadAndMergeAllSkills:# Actresult = await service.load_and_merge_all_skills(- sandbox, 'owner/repo', '/workspace', 'http://localhost:8000'+ sandbox, 'owner/repo', '/workspace/repo', 'http://localhost:8000')# Assertdiff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.pyindex b203c240f9..d9f79f79e2 100644--- a/tests/unit/app_server/test_live_status_app_conversation_service.py+++ b/tests/unit/app_server/test_live_status_app_conversation_service.py@@ -1199,6 +1199,9 @@ class TestLiveStatusAppConversationService:self.service._configure_llm_and_mcp.assert_called_once_with(self.mock_user, 'gpt-4')+ # When selected_repository='test/repo', project_dir is resolved+ # to '/test/dir/repo' via get_project_dir. All downstream calls+ # (agent context, workspace, skills) must use this path.self.service._create_agent_with_context.assert_called_once_with(mock_llm,AgentType.DEFAULT,@@ -1207,7 +1210,7 @@ class TestLiveStatusAppConversationService:self.mock_user.condenser_max_size,secrets=mock_secrets,git_provider=ProviderType.GITHUB,- working_dir='/test/dir',+ working_dir='/test/dir/repo',)self.service._finalize_conversation_request.assert_called_once()@@ -1989,6 +1992,111 @@ class TestLiveStatusAppConversationService:assert stdio_server['command'] == 'npx'assert stdio_server['env'] == {'TOKEN': 'value'}+ # ------------------------------------------------------------------ #+ # Regression tests: workspace.working_dir == project_dir #+ # ------------------------------------------------------------------ #++ def test_get_project_dir_with_repo(self):+ """get_project_dir appends repo name to working_dir."""+ from openhands.app_server.app_conversation.app_conversation_service_base import (+ get_project_dir,+ )++ assert (+ get_project_dir('/workspace/project', 'OpenHands/software-agent-sdk')+ == '/workspace/project/software-agent-sdk'+ )+ assert get_project_dir('/w', 'org/repo-name') == '/w/repo-name'++ def test_get_project_dir_without_repo(self):+ """get_project_dir returns working_dir unchanged when no repo selected."""+ from openhands.app_server.app_conversation.app_conversation_service_base import (+ get_project_dir,+ )++ assert get_project_dir('/workspace/project', None) == '/workspace/project'+ assert get_project_dir('/workspace/project', '') == '/workspace/project'++ @pytest.mark.asyncio+ async def test_build_request_workspace_uses_project_dir(self):+ """workspace.working_dir in StartConversationRequest must equal project_dir.++ This is the root cause of the V1 hook-stop bug: if workspace.working_dir+ points to the sandbox mount root (/workspace/project) instead of the+ cloned repo (/workspace/project/<repo>), the agent's CWD is wrong and+ .openhands/hooks/on_stop.sh is not found.+ """+ self.mock_user_context.get_user_info.return_value = self.mock_user++ mock_secrets = {'GITHUB_TOKEN': Mock()}+ mock_llm = Mock(spec=LLM)+ mock_agent = Mock(spec=Agent)++ self.service._setup_secrets_for_git_providers = AsyncMock(+ return_value=mock_secrets+ )+ self.service._configure_llm_and_mcp = AsyncMock(return_value=(mock_llm, {}))+ self.service._create_agent_with_context = Mock(return_value=mock_agent)++ captured = {}++ async def capture_finalize(+ agent, conversation_id, user, workspace, *args, **kwargs+ ):+ captured['workspace_working_dir'] = workspace.working_dir+ return Mock(spec=StartConversationRequest)++ self.service._finalize_conversation_request = AsyncMock(+ side_effect=capture_finalize+ )++ await self.service._build_start_conversation_request_for_user(+ sandbox=self.mock_sandbox,+ initial_message=None,+ system_message_suffix=None,+ git_provider=None,+ working_dir='/workspace/project',+ selected_repository='OpenHands/software-agent-sdk',+ )++ assert (+ captured['workspace_working_dir'] == '/workspace/project/software-agent-sdk'+ ), 'workspace.working_dir must point to the repo root, not the sandbox mount'++ @pytest.mark.asyncio+ async def test_build_request_no_repo_workspace_unchanged(self):+ """Without selected_repository, workspace.working_dir == sandbox working_dir."""+ self.mock_user_context.get_user_info.return_value = self.mock_user++ self.service._setup_secrets_for_git_providers = AsyncMock(return_value={})+ self.service._configure_llm_and_mcp = AsyncMock(+ return_value=(Mock(spec=LLM), {})+ )+ self.service._create_agent_with_context = Mock(return_value=Mock(spec=Agent))++ captured = {}++ async def capture_finalize(+ agent, conversation_id, user, workspace, *args, **kwargs+ ):+ captured['workspace_working_dir'] = workspace.working_dir+ return Mock(spec=StartConversationRequest)++ self.service._finalize_conversation_request = AsyncMock(+ side_effect=capture_finalize+ )++ await self.service._build_start_conversation_request_for_user(+ sandbox=self.mock_sandbox,+ initial_message=None,+ system_message_suffix=None,+ git_provider=None,+ working_dir='/workspace/project',+ selected_repository=None,+ )++ assert captured['workspace_working_dir'] == '/workspace/project'+class TestPluginHandling:"""Test cases for plugin-related functionality in LiveStatusAppConversationService."""