Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: proxy runtime git/changes and git/diff via app-conversations (#14606)

Hiep Le982994cb8e36
diff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.py
index 1366876094..fe24994c56 100644
--- a/openhands/app_server/app_conversation/app_conversation_router.py
+++ b/openhands/app_server/app_conversation/app_conversation_router.py
@@ -9,7 +9,7 @@ import sys
import tempfile
from dataclasses import dataclass
from datetime import datetime
-from typing import Annotated, AsyncGenerator, Literal
+from typing import Annotated, Any, AsyncGenerator, Literal
from uuid import UUID
import httpx
@@ -1057,6 +1057,140 @@ async def read_conversation_file(
return ''
+async def _proxy_git_runtime_call(
+ conversation_id: UUID,
+ runtime_path: str,
+ path: str,
+ ref: str | None,
+ app_conversation_service: AppConversationService,
+ sandbox_service: SandboxService,
+ sandbox_spec_service: SandboxSpecService,
+ httpx_client: httpx.AsyncClient,
+) -> Any:
+ """Resolve the conversation's runtime and proxy a GET to ``runtime_path``.
+
+ Browsers can't reach runtime sandboxes directly (no CORS for non-localhost
+ origins on most paths), so the frontend hits these endpoints on the cloud
+ API host instead and we make the runtime hop server-side using the
+ sandbox's session API key.
+ """
+ ctx = await _get_agent_server_context(
+ conversation_id,
+ app_conversation_service,
+ sandbox_service,
+ sandbox_spec_service,
+ )
+ if isinstance(ctx, JSONResponse):
+ raise HTTPException(
+ status_code=ctx.status_code,
+ detail=f'Conversation {conversation_id} is not reachable',
+ )
+ if ctx is None:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail='Sandbox is paused; resume it before reading git state.',
+ )
+
+ headers = {'X-Session-API-Key': ctx.session_api_key} if ctx.session_api_key else {}
+ params: dict[str, str] = {'path': path}
+ if ref is not None:
+ params['ref'] = ref
+
+ try:
+ upstream = await httpx_client.get(
+ f'{ctx.agent_server_url}{runtime_path}',
+ params=params,
+ headers=headers,
+ timeout=30.0,
+ )
+ upstream.raise_for_status()
+ return upstream.json()
+ except httpx.HTTPStatusError as e:
+ logger.error(
+ 'Agent server returned error during %s: %s - %s',
+ runtime_path,
+ e.response.status_code,
+ e.response.text,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f'Agent server error: {e.response.status_code}',
+ )
+ except (json.JSONDecodeError, httpx.DecodingError) as e:
+ logger.error('Agent server returned non-JSON during %s: %s', runtime_path, e)
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail='Agent server returned unexpected response.',
+ )
+ except httpx.RequestError as e:
+ logger.error('Failed to reach agent server during %s: %s', runtime_path, e)
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail='Failed to reach agent server.',
+ )
+
+
[email protected]('/{conversation_id}/git/changes')
+async def get_conversation_git_changes(
+ conversation_id: UUID,
+ path: Annotated[
+ str,
+ Query(
+ description=(
+ 'Absolute path to the git repository root (e.g. /workspace/project)'
+ ),
+ ),
+ ],
+ ref: Annotated[
+ str | None, Query(description='Optional git ref to diff against')
+ ] = None,
+ app_conversation_service: AppConversationService = (
+ app_conversation_service_dependency
+ ),
+ sandbox_service: SandboxService = sandbox_service_dependency,
+ sandbox_spec_service: SandboxSpecService = sandbox_spec_service_dependency,
+ httpx_client: httpx.AsyncClient = httpx_client_dependency,
+) -> Any:
+ """Proxy ``GET /api/git/changes`` on the conversation's runtime."""
+ return await _proxy_git_runtime_call(
+ conversation_id,
+ '/api/git/changes',
+ path,
+ ref,
+ app_conversation_service,
+ sandbox_service,
+ sandbox_spec_service,
+ httpx_client,
+ )
+
+
[email protected]('/{conversation_id}/git/diff')
+async def get_conversation_git_diff(
+ conversation_id: UUID,
+ path: Annotated[str, Query(description='The file path to diff')],
+ ref: Annotated[
+ str | None, Query(description='Optional git ref to diff against')
+ ] = None,
+ app_conversation_service: AppConversationService = (
+ app_conversation_service_dependency
+ ),
+ sandbox_service: SandboxService = sandbox_service_dependency,
+ sandbox_spec_service: SandboxSpecService = sandbox_spec_service_dependency,
+ httpx_client: httpx.AsyncClient = httpx_client_dependency,
+) -> Any:
+ """Proxy ``GET /api/git/diff`` on the conversation's runtime."""
+ return await _proxy_git_runtime_call(
+ conversation_id,
+ '/api/git/diff',
+ path,
+ ref,
+ app_conversation_service,
+ sandbox_service,
+ sandbox_spec_service,
+ httpx_client,
+ )
+
+
@router.get('/{conversation_id}/skills')
async def get_conversation_skills(
conversation_id: UUID,
diff --git a/tests/unit/app_server/test_app_conversation_router.py b/tests/unit/app_server/test_app_conversation_router.py
index 01e56c9b09..e8a41c2dc0 100644
--- a/tests/unit/app_server/test_app_conversation_router.py
+++ b/tests/unit/app_server/test_app_conversation_router.py
@@ -4,6 +4,7 @@ This module tests the batch_get_app_conversations endpoint,
focusing on UUID string parsing, validation, and error handling.
"""
+import json
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
@@ -22,6 +23,8 @@ from openhands.app_server.app_conversation.app_conversation_router import (
AgentServerContext,
batch_get_app_conversations,
count_app_conversations,
+ get_conversation_git_changes,
+ get_conversation_git_diff,
search_app_conversations,
switch_conversation_profile,
)
@@ -808,3 +811,274 @@ class TestSwitchConversationProfile:
sandbox_spec_service=MagicMock(),
httpx_client=client,
)
+
+
+def _make_get_httpx_client(get_return=None, get_side_effect=None) -> AsyncMock:
+ client = AsyncMock(spec=httpx.AsyncClient)
+ if get_side_effect is not None:
+ client.get = AsyncMock(side_effect=get_side_effect)
+ else:
+ response = get_return or MagicMock()
+ client.get = AsyncMock(return_value=response)
+ return client
+
+
+class TestGitProxyEndpoints:
+ """Test suite for /git/changes and /git/diff runtime proxy endpoints.
+
+ These endpoints exist so the browser can avoid hitting the runtime
+ sandbox URL directly (which fails CORS for non-localhost origins).
+ They resolve the conversation's runtime via ``_get_agent_server_context``
+ and forward the GET server-side using the sandbox's session API key.
+ """
+
+ async def test_changes_forwards_path_ref_and_session_key_to_runtime(self):
+ """Happy path: GET /git/changes calls runtime /api/git/changes with
+ the right URL, params, X-Session-API-Key header, and returns the
+ upstream JSON unchanged."""
+ # Arrange
+ conv_id = uuid4()
+ ctx = _make_agent_server_context(conv_id)
+ upstream_payload = [
+ {'status': 'UPDATED', 'path': 'src/foo.py'},
+ {'status': 'ADDED', 'path': 'src/bar.py'},
+ ]
+ upstream_response = MagicMock()
+ upstream_response.raise_for_status = MagicMock()
+ upstream_response.json = MagicMock(return_value=upstream_payload)
+ client = _make_get_httpx_client(get_return=upstream_response)
+
+ # Act
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ result = await get_conversation_git_changes(
+ conversation_id=conv_id,
+ path='/workspace/project',
+ ref='HEAD',
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ # Assert
+ assert result == upstream_payload
+ client.get.assert_awaited_once_with(
+ 'http://agent.test/api/git/changes',
+ params={'path': '/workspace/project', 'ref': 'HEAD'},
+ headers={'X-Session-API-Key': 'sess-key'},
+ timeout=30.0,
+ )
+
+ async def test_diff_routes_to_diff_runtime_path(self):
+ """``/git/diff`` proxies to ``/api/git/diff`` (not /changes)."""
+ # Arrange
+ conv_id = uuid4()
+ ctx = _make_agent_server_context(conv_id)
+ upstream_response = MagicMock()
+ upstream_response.raise_for_status = MagicMock()
+ upstream_response.json = MagicMock(
+ return_value={'modified': 'new', 'original': 'old'},
+ )
+ client = _make_get_httpx_client(get_return=upstream_response)
+
+ # Act
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ await get_conversation_git_diff(
+ conversation_id=conv_id,
+ path='/workspace/project/file.py',
+ ref=None,
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ # Assert: URL targets /api/git/diff and the optional ref param is omitted
+ client.get.assert_awaited_once_with(
+ 'http://agent.test/api/git/diff',
+ params={'path': '/workspace/project/file.py'},
+ headers={'X-Session-API-Key': 'sess-key'},
+ timeout=30.0,
+ )
+
+ async def test_returns_404_when_conversation_not_reachable(self):
+ """``_get_agent_server_context`` JSONResponse β†’ mirrored as
+ ``HTTPException`` so the cloud surface returns the same status."""
+ # Arrange
+ helper_response = JSONResponse(
+ status_code=status.HTTP_404_NOT_FOUND,
+ content={'error': 'Conversation not found'},
+ )
+
+ # Act + Assert
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=helper_response),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await get_conversation_git_changes(
+ conversation_id=uuid4(),
+ path='/workspace/project',
+ ref=None,
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=_make_get_httpx_client(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
+
+ async def test_returns_409_when_sandbox_paused(self):
+ """``_get_agent_server_context`` None (paused) β†’ 409 Conflict."""
+ # Act + Assert
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=None),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await get_conversation_git_changes(
+ conversation_id=uuid4(),
+ path='/workspace/project',
+ ref=None,
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=_make_get_httpx_client(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_409_CONFLICT
+ assert 'paused' in exc_info.value.detail.lower()
+
+ async def test_returns_502_when_runtime_returns_http_error(self):
+ """A 4xx/5xx from the runtime is folded into a 502 with the upstream
+ status code preserved in the detail."""
+ # Arrange
+ conv_id = uuid4()
+ ctx = _make_agent_server_context(conv_id)
+ bad_response = MagicMock()
+ bad_response.status_code = 500
+ bad_response.text = 'runtime crashed'
+ bad_response.raise_for_status = MagicMock(
+ side_effect=httpx.HTTPStatusError(
+ 'boom',
+ request=MagicMock(),
+ response=bad_response,
+ ),
+ )
+ client = _make_get_httpx_client(get_return=bad_response)
+
+ # Act + Assert
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await get_conversation_git_changes(
+ conversation_id=conv_id,
+ path='/workspace/project',
+ ref=None,
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
+ assert '500' in exc_info.value.detail
+
+ async def test_returns_502_when_runtime_unreachable(self):
+ """A network-level RequestError is folded into a 502."""
+ # Arrange
+ conv_id = uuid4()
+ ctx = _make_agent_server_context(conv_id)
+ client = _make_get_httpx_client(
+ get_side_effect=httpx.RequestError('connection refused'),
+ )
+
+ # Act + Assert
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await get_conversation_git_changes(
+ conversation_id=conv_id,
+ path='/workspace/project',
+ ref=None,
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
+ assert 'reach agent server' in exc_info.value.detail.lower()
+
+ async def test_returns_502_when_runtime_returns_non_json(self):
+ """A 200 OK whose body fails to decode (``json.JSONDecodeError``) is
+ folded into a 502 rather than escaping as an unhandled 500."""
+ # Arrange
+ conv_id = uuid4()
+ ctx = _make_agent_server_context(conv_id)
+ bad_response = MagicMock()
+ bad_response.raise_for_status = MagicMock()
+ bad_response.json = MagicMock(
+ side_effect=json.JSONDecodeError('Expecting value', '<html>', 0),
+ )
+ client = _make_get_httpx_client(get_return=bad_response)
+
+ # Act + Assert
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await get_conversation_git_changes(
+ conversation_id=conv_id,
+ path='/workspace/project',
+ ref=None,
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
+ assert 'unexpected response' in exc_info.value.detail.lower()
+
+ async def test_diff_returns_409_when_sandbox_paused(self):
+ """Confirms ``/git/diff`` shares the same error wiring as ``/changes``:
+ a paused sandbox (helper ``None``) surfaces as 409 Conflict."""
+ # Act + Assert
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=None),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await get_conversation_git_diff(
+ conversation_id=uuid4(),
+ path='/workspace/project/file.py',
+ ref=None,
+ app_conversation_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=_make_get_httpx_client(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_409_CONFLICT
+ assert 'paused' in exc_info.value.detail.lower()