Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove deprecated V0 FastAPI endpoints (#13952)

Tim O'Farrell3b264dd419c8
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py
index fd6fb31682..d04e90568e 100644
--- a/enterprise/saas_server.py
+++ b/enterprise/saas_server.py
@@ -47,7 +47,6 @@ from server.routes.org_invitations import ( # noqa: E402
from server.routes.orgs import org_router # noqa: E402
from server.routes.readiness import readiness_router # noqa: E402
from server.routes.service import service_router # noqa: E402
-from server.routes.user import saas_user_router # noqa: E402
from server.routes.user_app_settings import user_app_settings_router # noqa: E402
from server.routes.users_v1 import ( # noqa: E402
override_users_me_endpoint,
@@ -86,7 +85,6 @@ base_app.include_router(readiness_router) # Add routes for readiness checks
base_app.include_router(api_router) # Add additional route for github auth
base_app.include_router(oauth_router) # Add additional route for oauth callback
base_app.include_router(oauth_device_router) # Add OAuth 2.0 Device Flow routes
-base_app.include_router(saas_user_router) # Add additional route SAAS user calls
base_app.include_router(user_app_settings_router) # Add routes for user app settings
base_app.include_router(
billing_router
diff --git a/enterprise/server/routes/user.py b/enterprise/server/routes/user.py
deleted file mode 100644
index c88878f5d4..0000000000
--- a/enterprise/server/routes/user.py
+++ /dev/null
@@ -1,441 +0,0 @@
-from typing import Any
-
-from fastapi import APIRouter, Depends, Query, status
-from fastapi.responses import JSONResponse
-from pydantic import SecretStr
-from server.auth.token_manager import TokenManager
-from storage.user_store import UserStore
-from utils.identity import resolve_display_name
-
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.integrations.provider import (
- PROVIDER_TOKEN_TYPE,
- ProviderHandler,
-)
-from openhands.integrations.service_types import (
- Branch,
- PaginatedBranchesResponse,
- ProviderType,
- Repository,
- SuggestedTask,
- User,
-)
-from openhands.microagent.types import (
- MicroagentContentResponse,
- MicroagentResponse,
-)
-from openhands.server.routes.git import (
- get_repository_branches,
- get_repository_microagent_content,
- get_repository_microagents,
- get_suggested_tasks,
- get_user,
- get_user_installations,
- get_user_repositories,
- search_branches,
- search_repositories,
-)
-from openhands.server.user_auth import (
- get_access_token,
- get_provider_tokens,
- get_user_id,
-)
-
-saas_user_router = APIRouter(prefix='/api/user', dependencies=get_dependencies())
-token_manager = TokenManager()
-
-
-@saas_user_router.get(
- '/installations',
- response_model=list[str],
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/installations` instead.',
-)
-async def saas_get_user_installations(
- provider: ProviderType,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-):
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=[],
- )
- if retval is not None:
- return retval
-
- return await get_user_installations(
- provider=provider,
- provider_tokens=provider_tokens,
- access_token=access_token,
- user_id=user_id,
- )
-
-
-@saas_user_router.get('/git-organizations')
-async def saas_get_user_git_organizations(
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-):
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value={},
- )
- if retval is not None:
- return retval
- # _check_idp returned None (tokens refreshed on Keycloak side),
- # but provider_tokens is still None for this request.
- return JSONResponse(
- content='Git provider token required.',
- status_code=status.HTTP_401_UNAUTHORIZED,
- )
-
- client = ProviderHandler(
- provider_tokens=provider_tokens,
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
-
- # SaaS users sign in with one provider at a time
- provider = next(iter(provider_tokens))
-
- if provider == ProviderType.GITHUB:
- orgs = await client.get_github_organizations()
- elif provider == ProviderType.GITLAB:
- orgs = await client.get_gitlab_groups()
- elif provider == ProviderType.BITBUCKET:
- orgs = await client.get_bitbucket_workspaces()
- else:
- return JSONResponse(
- content=f"Provider {provider.value} doesn't support git organizations",
- status_code=status.HTTP_400_BAD_REQUEST,
- )
-
- return {
- 'provider': provider.value,
- 'organizations': orgs,
- }
-
-
-@saas_user_router.get(
- '/repositories',
- response_model=list[Repository],
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/repositories` instead.',
-)
-async def saas_get_user_repositories(
- sort: str = 'pushed',
- selected_provider: ProviderType | None = None,
- page: int | None = None,
- per_page: int | None = None,
- installation_id: str | None = None,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[Repository] | JSONResponse:
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=[],
- )
- if retval is not None:
- return retval
-
- return await get_user_repositories(
- sort=sort,
- selected_provider=selected_provider,
- page=page,
- per_page=per_page,
- installation_id=installation_id,
- provider_tokens=provider_tokens,
- access_token=access_token,
- user_id=user_id,
- )
-
-
-@saas_user_router.get('/info', response_model=User, deprecated=True)
-async def saas_get_user(
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> User | JSONResponse:
- """Get the current user git info. Use GET /api/v1/users/git-info instead"""
- if not provider_tokens:
- if not access_token:
- return JSONResponse(
- content='User is not authenticated.',
- status_code=status.HTTP_401_UNAUTHORIZED,
- )
- user_info = await token_manager.get_user_info(access_token.get_secret_value())
- # Prefer email from DB; fall back to Keycloak if not yet persisted
- email = user_info.email
- sub = user_info.sub
- if sub:
- db_user = await UserStore.get_user_by_id(sub)
- if db_user and db_user.email is not None:
- email = db_user.email
-
- user_info_dict = user_info.model_dump(exclude_none=True)
- retval = await _check_idp(
- access_token=access_token,
- default_value=User(
- id=sub,
- login=user_info.preferred_username or '',
- avatar_url='',
- email=email,
- name=resolve_display_name(user_info_dict),
- company=user_info.company,
- ),
- user_info=user_info_dict,
- )
- if retval is not None:
- return retval
-
- return await get_user(
- provider_tokens=provider_tokens, access_token=access_token, user_id=user_id
- )
-
-
-@saas_user_router.get('/search/repositories', response_model=list[Repository])
-async def saas_search_repositories(
- query: str,
- per_page: int = 5,
- sort: str = 'stars',
- order: str = 'desc',
- selected_provider: ProviderType | None = None,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[Repository] | JSONResponse:
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=[],
- )
- if retval is not None:
- return retval
-
- return await search_repositories(
- query=query,
- per_page=per_page,
- sort=sort,
- order=order,
- selected_provider=selected_provider,
- provider_tokens=provider_tokens,
- access_token=access_token,
- user_id=user_id,
- )
-
-
-@saas_user_router.get('/suggested-tasks', response_model=list[SuggestedTask])
-async def saas_get_suggested_tasks(
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[SuggestedTask] | JSONResponse:
- """Get suggested tasks for the authenticated user across their most recently pushed repositories.
-
- Returns:
- - PRs owned by the user
- - Issues assigned to the user.
- """
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=[],
- )
- if retval is not None:
- return retval
-
- return await get_suggested_tasks(
- provider_tokens=provider_tokens, access_token=access_token, user_id=user_id
- )
-
-
-@saas_user_router.get('/repository/branches', response_model=PaginatedBranchesResponse)
-async def saas_get_repository_branches(
- repository: str,
- page: int = 1,
- per_page: int = 30,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> PaginatedBranchesResponse | JSONResponse:
- """Get branches for a repository.
-
- Args:
- repository: The repository name in the format 'owner/repo'
-
- Returns:
- A list of branches for the repository
- """
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=[],
- )
- if retval is not None:
- return retval
-
- return await get_repository_branches(
- repository=repository,
- page=page,
- per_page=per_page,
- provider_tokens=provider_tokens,
- access_token=access_token,
- user_id=user_id,
- )
-
-
-@saas_user_router.get('/search/branches', response_model=list[Branch])
-async def saas_search_branches(
- repository: str,
- query: str,
- per_page: int = 30,
- selected_provider: ProviderType | None = None,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[Branch] | JSONResponse:
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=[],
- )
- if retval is not None:
- return retval
-
- return await search_branches(
- repository=repository,
- query=query,
- per_page=per_page,
- selected_provider=selected_provider,
- provider_tokens=provider_tokens,
- access_token=access_token,
- user_id=user_id,
- )
-
-
-@saas_user_router.get(
- '/repository/{repository_name:path}/microagents',
- response_model=list[MicroagentResponse],
-)
-async def saas_get_repository_microagents(
- repository_name: str,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[MicroagentResponse] | JSONResponse:
- """Scan the microagents directory of a repository and return the list of microagents.
-
- The microagents directory location depends on the git provider and actual repository name:
- - If git provider is not GitLab and actual repository name is ".openhands": scans "microagents" folder
- - If git provider is GitLab and actual repository name is "openhands-config": scans "microagents" folder
- - Otherwise: scans ".openhands/microagents" folder
-
- Note: This API returns microagent metadata without content for performance.
- Use the separate content API to fetch individual microagent content.
-
- Args:
- repository_name: Repository name in the format 'owner/repo' or 'domain/owner/repo'
- provider_tokens: Provider tokens for authentication
- access_token: Access token for external authentication
- user_id: User ID for authentication
-
- Returns:
- List of microagents found in the repository's microagents directory (without content)
- """
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=[],
- )
- if retval is not None:
- return retval
-
- return await get_repository_microagents(
- repository_name=repository_name,
- provider_tokens=provider_tokens,
- access_token=access_token,
- user_id=user_id,
- )
-
-
-@saas_user_router.get(
- '/repository/{repository_name:path}/microagents/content',
- response_model=MicroagentContentResponse,
-)
-async def saas_get_repository_microagent_content(
- repository_name: str,
- file_path: str = Query(
- ..., description='Path to the microagent file within the repository'
- ),
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> MicroagentContentResponse | JSONResponse:
- """Fetch the content of a specific microagent file from a repository.
-
- Args:
- repository_name: Repository name in the format 'owner/repo' or 'domain/owner/repo'
- file_path: Query parameter - Path to the microagent file within the repository
- provider_tokens: Provider tokens for authentication
- access_token: Access token for external authentication
- user_id: User ID for authentication
-
- Returns:
- Microagent file content and metadata
-
- Example:
- GET /api/user/repository/owner/repo/microagents/content?file_path=.openhands/microagents/my-agent.md
- """
- if not provider_tokens:
- retval = await _check_idp(
- access_token=access_token,
- default_value=MicroagentContentResponse(content='', path=''),
- )
- if retval is not None:
- return retval
-
- return await get_repository_microagent_content(
- repository_name=repository_name,
- file_path=file_path,
- provider_tokens=provider_tokens,
- access_token=access_token,
- user_id=user_id,
- )
-
-
-async def _check_idp(
- access_token: SecretStr | None,
- default_value: Any,
- user_info: dict | None = None,
-):
- if not access_token:
- return JSONResponse(
- content='User is not authenticated.',
- status_code=status.HTTP_401_UNAUTHORIZED,
- )
- if user_info is None:
- user_info_model = await token_manager.get_user_info(
- access_token.get_secret_value()
- )
- user_info = user_info_model.model_dump(exclude_none=True)
- idp: str | None = user_info.get('identity_provider')
- if not idp:
- return JSONResponse(
- content='IDP not found.',
- status_code=status.HTTP_401_UNAUTHORIZED,
- )
- if ':' in idp:
- idp, _ = idp.rsplit(':', 1)
-
- # Will return empty dict if IDP doesn't support provider tokens
- if not await token_manager.get_idp_tokens_from_keycloak(
- access_token.get_secret_value(), ProviderType(idp)
- ):
- return default_value
- return None
diff --git a/enterprise/tests/unit/test_user_git_organizations.py b/enterprise/tests/unit/test_user_git_organizations.py
deleted file mode 100644
index 6f0b744e19..0000000000
--- a/enterprise/tests/unit/test_user_git_organizations.py
+++ /dev/null
@@ -1,141 +0,0 @@
-"""Tests for the GET /api/user/git-organizations endpoint.
-
-This endpoint returns git organizations for the user's active provider
-in SaaS mode (single provider at a time).
-"""
-
-from types import MappingProxyType
-from unittest.mock import AsyncMock, patch
-
-import pytest
-from fastapi.responses import JSONResponse
-from pydantic import SecretStr
-
-from openhands.integrations.provider import ProviderToken
-from openhands.integrations.service_types import ProviderType
-
-
-def github_provider_tokens():
- return MappingProxyType(
- {ProviderType.GITHUB: ProviderToken(token=SecretStr('gh-token'))}
- )
-
-
-def gitlab_provider_tokens():
- return MappingProxyType(
- {ProviderType.GITLAB: ProviderToken(token=SecretStr('gl-token'))}
- )
-
-
-def bitbucket_provider_tokens():
- return MappingProxyType(
- {ProviderType.BITBUCKET: ProviderToken(token=SecretStr('bb-token'))}
- )
-
-
-def azure_devops_provider_tokens():
- return MappingProxyType(
- {ProviderType.AZURE_DEVOPS: ProviderToken(token=SecretStr('az-token'))}
- )
-
-
-def mock_check_idp():
- with patch('server.routes.user._check_idp', new_callable=AsyncMock) as mock_fn:
- yield mock_fn
-
-
-async def test_no_provider_tokens_falls_back_to_idp(mock_check_idp):
- """When no provider tokens exist, falls back to IDP check."""
- from server.routes.user import saas_get_user_git_organizations
-
- mock_check_idp.return_value = {}
-
- result = await saas_get_user_git_organizations(
- provider_tokens=None,
- access_token=SecretStr('token'),
- user_id='user-1',
- )
-
- assert result == {}
- mock_check_idp.assert_called_once()
-
-
-async def test_unsupported_provider_returns_400(azure_devops_provider_tokens):
- """Unsupported provider returns a 400 error."""
- from server.routes.user import saas_get_user_git_organizations
-
- with patch('server.routes.user.ProviderHandler'):
- result = await saas_get_user_git_organizations(
- provider_tokens=azure_devops_provider_tokens,
- access_token=SecretStr('token'),
- user_id='user-1',
- )
-
- assert isinstance(result, JSONResponse)
- assert result.status_code == 400
-
-
- 'provider_tokens_fixture, mock_method, mock_return, expected_provider',
- [
- (
- 'github_provider_tokens',
- 'get_organizations_from_installations',
- ['All-Hands-AI', 'OpenHands'],
- 'github',
- ),
- (
- 'gitlab_provider_tokens',
- 'get_user_groups',
- ['my-team', 'open-source'],
- 'gitlab',
- ),
- (
- 'bitbucket_provider_tokens',
- 'get_installations',
- ['my-workspace'],
- 'bitbucket',
- ),
- ],
- ids=['github', 'gitlab', 'bitbucket'],
-)
-async def test_provider_routing_with_real_handler(
- provider_tokens_fixture,
- mock_method,
- mock_return,
- expected_provider,
- request,
-):
- """Each provider routes to the correct service method and returns the expected JSON structure.
-
- Uses a real ProviderHandler so the endpoint's if/elif routing and ProviderHandler's
- delegation are both exercised. Only the low-level git service call is mocked.
- """
- from server.routes.user import saas_get_user_git_organizations
-
- provider_tokens = request.getfixturevalue(provider_tokens_fixture)
-
- with patch(
- 'openhands.integrations.provider.ProviderHandler.get_service'
- ) as mock_get_service:
- mock_service = mock_get_service.return_value
- setattr(mock_service, mock_method, AsyncMock(return_value=mock_return))
-
- result = await saas_get_user_git_organizations(
- provider_tokens=provider_tokens,
- access_token=SecretStr('token'),
- user_id='user-1',
- )
-
- assert result == {
- 'provider': expected_provider,
- 'organizations': mock_return,
- }
diff --git a/enterprise/tests/unit/test_user_route_fallback.py b/enterprise/tests/unit/test_user_route_fallback.py
deleted file mode 100644
index cb43301f80..0000000000
--- a/enterprise/tests/unit/test_user_route_fallback.py
+++ /dev/null
@@ -1,261 +0,0 @@
-"""Tests for the fallback User path in the /api/user/info endpoint.
-
-When a user authenticates via Keycloak without provider tokens (e.g., SAML, enterprise SSO),
-the endpoint constructs a User from OIDC claims. These tests verify that name and company
-fields are correctly populated from Keycloak claims in this fallback path.
-"""
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from pydantic import SecretStr
-
-from openhands.integrations.service_types import User
-
-
-def mock_token_manager():
- """Mock the token_manager used by user.py routes."""
- with patch('server.routes.user.token_manager') as mock_tm:
- yield mock_tm
-
-
-def mock_check_idp():
- """Mock _check_idp to pass through the default_value (the fallback User).
-
- This isolates the test to just the User construction logic in saas_get_user,
- without needing to set up Keycloak IDP token checks.
- """
- with patch('server.routes.user._check_idp') as mock_fn:
- # Return the default_value argument that was passed to _check_idp
- mock_fn.side_effect = lambda **kwargs: kwargs.get('default_value')
- yield mock_fn
-
-
-def mock_user_store():
- """Mock UserStore.get_user_by_id to return None by default."""
- with patch(
- 'server.routes.user.UserStore.get_user_by_id',
- new_callable=AsyncMock,
- return_value=None,
- ) as mock_fn:
- yield mock_fn
-
-
-async def test_fallback_user_includes_name_from_name_claim(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When Keycloak provides a 'name' claim, the fallback User should include it."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- name='Jane Doe',
- preferred_username='j.doe',
- )
- )
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.name == 'Jane Doe'
- assert result.email == '[email protected]'
-
-
-async def test_fallback_user_combines_given_and_family_name(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When 'name' is absent, combine given_name + family_name."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- given_name='Jane',
- family_name='Doe',
- preferred_username='j.doe',
- )
- )
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.name == 'Jane Doe'
-
-
-async def test_fallback_user_name_is_none_when_no_name_claims(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When no name claims exist, name should be None."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- preferred_username='j.doe',
- )
- )
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.name is None
-
-
-async def test_fallback_user_includes_company_claim(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When Keycloak provides a 'company' claim, include it in the User."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- name='Jane Doe',
- preferred_username='j.doe',
- company='Acme Corp',
- )
- )
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.company == 'Acme Corp'
-
-
-async def test_fallback_user_company_is_none_when_absent(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When 'company' is not in Keycloak claims, company should be None."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- name='Jane Doe',
- preferred_username='j.doe',
- )
- )
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.company is None
-
-
-async def test_fallback_user_email_from_db_when_available(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When User.email is stored in DB, use it instead of Keycloak's live email."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- preferred_username='j.doe',
- )
- )
-
- mock_db_user = MagicMock()
- mock_db_user.email = '[email protected]'
- mock_user_store.return_value = mock_db_user
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.email == '[email protected]'
-
-
-async def test_fallback_user_email_falls_back_to_keycloak_when_db_null(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When User.email is NULL in DB, fall back to Keycloak's email."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- preferred_username='j.doe',
- )
- )
-
- mock_db_user = MagicMock()
- mock_db_user.email = None
- mock_user_store.return_value = mock_db_user
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.email == '[email protected]'
-
-
-async def test_fallback_user_email_falls_back_to_keycloak_when_no_db_user(
- mock_token_manager, mock_check_idp, mock_user_store, create_keycloak_user_info
-):
- """When DB user doesn't exist, fall back to Keycloak's email."""
- from server.routes.user import saas_get_user
-
- mock_token_manager.get_user_info = AsyncMock(
- return_value=create_keycloak_user_info(
- sub='248289761001',
- preferred_username='j.doe',
- )
- )
-
- # mock_user_store already returns None by default
-
- result = await saas_get_user(
- provider_tokens=None,
- access_token=SecretStr('test-token'),
- user_id='248289761001',
- )
-
- assert isinstance(result, User)
- assert result.email == '[email protected]'
diff --git a/openhands/app_server/settings/settings_router.py b/openhands/app_server/settings/settings_router.py
index a50e57679a..90398acc10 100644
--- a/openhands/app_server/settings/settings_router.py
+++ b/openhands/app_server/settings/settings_router.py
@@ -16,7 +16,6 @@ from openhands.integrations.provider import (
ProviderType,
)
from openhands.sdk.settings import AgentSettings, ConversationSettings
-from openhands.server.routes.secrets import invalidate_legacy_secrets_store
from openhands.server.settings import (
GETSettingsModel,
)
@@ -27,6 +26,7 @@ from openhands.server.user_auth import (
get_user_settings,
get_user_settings_store,
)
+from openhands.storage.data_models.secrets import Secrets
from openhands.storage.data_models.settings import Settings
from openhands.storage.secrets.secrets_store import SecretsStore
from openhands.storage.settings.settings_store import SettingsStore
@@ -247,3 +247,25 @@ async def load_settings_schema() -> dict[str, Any]:
async def load_conversation_settings_schema() -> dict[str, Any]:
"""Load the schema for conversations"""
return ConversationSettings.export_schema().model_dump(mode='json')
+
+
+async def invalidate_legacy_secrets_store(
+ settings: Settings, settings_store: SettingsStore, secrets_store: SecretsStore
+) -> Secrets | None:
+ """We are moving `secrets_store` (a field from `Settings` object) to its own dedicated store
+ This function moves the values from Settings to Secrets, and deletes the values in Settings
+ While this function in called multiple times, the migration only ever happens once
+ """
+ if len(settings.secrets_store.provider_tokens.items()) > 0:
+ user_secrets = Secrets(provider_tokens=settings.secrets_store.provider_tokens)
+ await secrets_store.store(user_secrets)
+
+ # Invalidate old tokens via settings store serializer
+ invalidated_secrets_settings = settings.model_copy(
+ update={'secrets_store': Secrets()}
+ )
+ await settings_store.store(invalidated_secrets_settings)
+
+ return user_secrets
+
+ return None
diff --git a/openhands/server/app.py b/openhands/server/app.py
index 8ecac2b462..52ca9c418e 100644
--- a/openhands/server/app.py
+++ b/openhands/server/app.py
@@ -27,21 +27,9 @@ from openhands.app_server import v1_router
from openhands.app_server.config import get_app_lifespan_service
from openhands.app_server.status.status_router import router as health_router
from openhands.integrations.service_types import AuthenticationError
-from openhands.server.routes.conversation import app as conversation_api_router
-from openhands.server.routes.feedback import app as feedback_api_router
-from openhands.server.routes.files import app as files_api_router
-from openhands.server.routes.git import app as git_api_router
-from openhands.server.routes.manage_conversations import (
- app as manage_conversation_api_router,
-)
from openhands.server.routes.mcp import mcp_server
-from openhands.server.routes.public import app as public_api_router
-from openhands.server.routes.secrets import app as secrets_router
from openhands.server.routes.security import app as security_api_router
-from openhands.server.routes.settings import app as settings_router
-from openhands.server.routes.trajectory import app as trajectory_router
-from openhands.server.shared import conversation_manager, server_config
-from openhands.server.types import AppMode
+from openhands.server.shared import conversation_manager
from openhands.version import get_version
mcp_app = mcp_server.http_app(path='/mcp', stateless_http=True)
@@ -88,17 +76,6 @@ async def authentication_error_handler(request: Request, exc: AuthenticationErro
)
-app.include_router(public_api_router)
-app.include_router(files_api_router)
app.include_router(security_api_router)
-app.include_router(feedback_api_router)
-app.include_router(conversation_api_router)
-app.include_router(manage_conversation_api_router)
-app.include_router(settings_router)
-app.include_router(secrets_router)
-if server_config.app_mode == AppMode.OPENHANDS:
- app.include_router(git_api_router)
-if server_config.enable_v1:
- app.include_router(v1_router.router)
-app.include_router(trajectory_router)
+app.include_router(v1_router.router)
app.include_router(health_router)
diff --git a/openhands/server/routes/conversation.py b/openhands/server/routes/conversation.py
deleted file mode 100644
index 4aa76a5896..0000000000
--- a/openhands/server/routes/conversation.py
+++ /dev/null
@@ -1,425 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import uuid
-
-from fastapi import APIRouter, Depends, HTTPException, Request, status
-from fastapi.responses import JSONResponse
-from pydantic import BaseModel
-
-from openhands.app_server.app_conversation.app_conversation_info_service import (
- AppConversationInfoService,
-)
-from openhands.app_server.app_conversation.app_conversation_models import (
- AppConversationInfo,
-)
-from openhands.app_server.config import depends_app_conversation_info_service
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.action.message import MessageAction
-from openhands.events.event_filter import EventFilter
-from openhands.events.event_store import EventStore
-from openhands.events.serialization.event import event_to_dict
-from openhands.memory.memory import Memory
-from openhands.microagent.types import InputMetadata
-from openhands.runtime.base import Runtime
-from openhands.server.session.conversation import ServerConversation
-from openhands.server.shared import conversation_manager, file_store
-from openhands.server.user_auth import get_user_id
-from openhands.server.utils import get_conversation, get_conversation_metadata
-from openhands.storage.data_models.conversation_metadata import ConversationMetadata
-
-app = APIRouter(
- prefix='/api/conversations/{conversation_id}', dependencies=get_dependencies()
-)
-
-# Dependency for app conversation service
-app_conversation_info_service_dependency = depends_app_conversation_info_service()
-
-
-async def _get_v1_conversation_info(
- conversation_id: str, app_conversation_info_service: AppConversationInfoService
-) -> AppConversationInfo | None:
- try:
- conversation_uuid = uuid.UUID(conversation_id)
- app_conversation_info = (
- await app_conversation_info_service.get_app_conversation_info(
- conversation_uuid
- )
- )
- return app_conversation_info
- except (ValueError, TypeError):
- # Not a valid UUID, so it's not a V1 conversation
- return None
- except Exception as e:
- # Service error, assume it's not a V1 conversation
- logger.debug(f'Failed to fetch V1 conversation {conversation_id}: {e}')
- return None
-
-
-def _get_v0_conversation_config(
- conversation: ServerConversation,
-) -> dict[str, str | None]:
- """Get configuration for a V0 conversation.
-
- Args:
- conversation: The server conversation object
-
- Returns:
- Dictionary with runtime_id and session_id from the runtime
- """
- runtime = conversation.runtime
- runtime_id = runtime.runtime_id if hasattr(runtime, 'runtime_id') else None
- session_id = runtime.sid if hasattr(runtime, 'sid') else None
-
- return {
- 'runtime_id': runtime_id,
- 'session_id': session_id,
- }
-
-
[email protected]('/config', deprecated=True)
-async def get_remote_runtime_config(
- conversation_id: str,
- app_conversation_info_service: AppConversationInfoService = app_conversation_info_service_dependency,
- user_id: str | None = Depends(get_user_id),
-) -> JSONResponse:
- """Retrieve the runtime configuration.
-
- .. deprecated::
- This endpoint is deprecated. The config is now returned as part of
- GET /api/v1/app-conversation/{conversation_id}. Use that endpoint instead.
-
- For V0 conversations: returns runtime_id and session_id from the runtime.
- For V1 conversations: returns sandbox_id as runtime_id and conversation_id as session_id.
- """
- # Check if this is a V1 conversation first
- v1_conversation_info = await _get_v1_conversation_info(
- conversation_id, app_conversation_info_service
- )
- if v1_conversation_info:
- # This is a V1 conversation
- return JSONResponse(
- content={
- 'runtime_id': v1_conversation_info.sandbox_id,
- 'session_id': conversation_id,
- },
- status_code=200,
- )
- else:
- # V0 conversation - get the conversation and use the existing logic
- conversation = await conversation_manager.attach_to_conversation(
- conversation_id, user_id
- )
- if not conversation:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f'Conversation {conversation_id} not found',
- )
- try:
- config = _get_v0_conversation_config(conversation)
- finally:
- await conversation_manager.detach_from_conversation(conversation)
-
- return JSONResponse(content=config)
-
-
[email protected]('/vscode-url', deprecated=True)
-async def get_vscode_url(
- conversation: ServerConversation = Depends(get_conversation),
-) -> JSONResponse:
- """Get the VSCode URL.
-
- This endpoint allows getting the VSCode URL.
-
- Args:
- request (Request): The incoming FastAPI request object.
-
- Returns:
- JSONResponse: A JSON response indicating the success of the operation.
-
- For V1 conversations, the VSCode URL is available in the sandbox's ``exposed_urls``
- field. Use ``GET /api/v1/sandboxes?id={sandbox_id}`` to retrieve sandbox information and use the name VSCODE.
- """
- try:
- runtime: Runtime = conversation.runtime
- logger.debug(f'Runtime type: {type(runtime)}')
- logger.debug(f'Runtime VSCode URL: {runtime.vscode_url}')
- return JSONResponse(
- status_code=status.HTTP_200_OK, content={'vscode_url': runtime.vscode_url}
- )
- except Exception as e:
- logger.error(f'Error getting VSCode URL: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={
- 'vscode_url': None,
- 'error': f'Error getting VSCode URL: {e}',
- },
- )
-
-
[email protected]('/web-hosts', deprecated=True)
-async def get_hosts(
- conversation: ServerConversation = Depends(get_conversation),
-) -> JSONResponse:
- """Get the hosts used by the runtime.
-
- This endpoint allows getting the hosts used by the runtime.
-
- Args:
- request (Request): The incoming FastAPI request object.
-
- Returns:
- JSONResponse: A JSON response indicating the success of the operation.
-
- For V1 conversations, web hosts are available in the sandbox's ``exposed_urls``
- field. Use ``GET /api/v1/sandboxes?id={sandbox_id}`` to retrieve sandbox information and use the name AGENT_SERVER.
- """
- try:
- runtime: Runtime = conversation.runtime
- logger.debug(f'Runtime type: {type(runtime)}')
- logger.debug(f'Runtime hosts: {runtime.web_hosts}')
- return JSONResponse(status_code=200, content={'hosts': runtime.web_hosts})
- except Exception as e:
- logger.error(f'Error getting runtime hosts: {e}')
- return JSONResponse(
- status_code=500,
- content={
- 'hosts': None,
- 'error': f'Error getting runtime hosts: {e}',
- },
- )
-
-
[email protected]('/events', deprecated=True)
-async def search_events(
- conversation_id: str,
- start_id: int = 0,
- end_id: int | None = None,
- reverse: bool = False,
- filter: EventFilter | None = None,
- limit: int = 20,
- metadata: ConversationMetadata = Depends(get_conversation_metadata),
- user_id: str | None = Depends(get_user_id),
-):
- """Search through the event stream with filtering and pagination.
-
- Args:
- conversation_id: The conversation ID
- start_id: Starting ID in the event stream. Defaults to 0
- end_id: Ending ID in the event stream
- reverse: Whether to retrieve events in reverse order. Defaults to False.
- filter: Filter for events
- limit: Maximum number of events to return. Must be between 1 and 100. Defaults to 20
- metadata: Conversation metadata (injected by dependency)
- user_id: User ID (injected by dependency)
-
- Returns:
- dict: Dictionary containing:
- - events: List of matching events
- - has_more: Whether there are more matching events after this batch
- Raises:
- HTTPException: If conversation is not found or access is denied
- ValueError: If limit is less than 1 or greater than 100
-
- Use the V1 endpoint ``GET /api/v1/events/search?conversation_id__eq={conversation_id}``
- instead, which provides enhanced filtering by event kind, timestamp ranges,
- and improved pagination.
- """
- if limit < 0 or limit > 100:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid limit'
- )
-
- # Create an event store to access the events directly
- event_store = EventStore(
- sid=conversation_id,
- file_store=file_store,
- user_id=user_id,
- )
-
- # Get matching events from the store
- events = list(
- event_store.search_events(
- start_id=start_id,
- end_id=end_id,
- reverse=reverse,
- filter=filter,
- limit=limit + 1,
- )
- )
-
- # Check if there are more events
- has_more = len(events) > limit
- if has_more:
- events = events[:limit] # Remove the extra event
-
- events_json = [event_to_dict(event) for event in events]
- return {
- 'events': events_json,
- 'has_more': has_more,
- }
-
-
[email protected]('/events', deprecated=True)
-async def add_event(
- request: Request, conversation: ServerConversation = Depends(get_conversation)
-):
- """Add an event to a conversation.
-
- For V1 conversations, events are managed through the sandbox webhook system.
- Use ``POST /api/v1/webhooks/events/{conversation_id}`` for event callbacks.
- """
- data = await request.json()
- await conversation_manager.send_event_to_conversation(conversation.sid, data)
- return JSONResponse({'success': True})
-
-
-class AddMessageRequest(BaseModel):
- """Request model for adding a message to a conversation."""
-
- message: str
-
-
[email protected]('/message', deprecated=True)
-async def add_message(
- data: AddMessageRequest,
- conversation: ServerConversation = Depends(get_conversation),
-):
- """Add a message to an existing conversation.
-
- This endpoint allows adding a user message to an existing conversation.
- The message will be processed by the agent in the conversation.
-
- Args:
- data: The request data containing the message text
- conversation: The conversation to add the message to (injected by dependency)
-
- Returns:
- JSONResponse: A JSON response indicating the success of the operation
-
- For V1 conversations, messages are handled through the agent server.
- Use the sandbox's exposed agent server URL to send messages.
- """
- try:
- # Create a MessageAction from the provided message text
- message_action = MessageAction(content=data.message)
-
- # Convert the action to a dictionary for sending to the conversation
- message_data = event_to_dict(message_action)
-
- # Send the message to the conversation
- await conversation_manager.send_event_to_conversation(
- conversation.sid, message_data
- )
-
- return JSONResponse({'success': True})
- except Exception as e:
- logger.error(f'Error adding message to conversation: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={
- 'success': False,
- 'error': f'Error adding message to conversation: {e}',
- },
- )
-
-
-class MicroagentResponse(BaseModel):
- """Response model for microagents endpoint."""
-
- name: str
- type: str
- content: str
- triggers: list[str] = []
- inputs: list[InputMetadata] = []
- tools: list[str] = []
-
-
[email protected]('/microagents', deprecated=True)
-async def get_microagents(
- conversation: ServerConversation = Depends(get_conversation),
-) -> JSONResponse:
- """Get all microagents associated with the conversation.
-
- This endpoint returns all repository and knowledge microagents that are loaded for the conversation.
-
- Returns:
- JSONResponse: A JSON response containing the list of microagents.
-
- Use the V1 endpoint ``GET /api/v1/app-conversations/{conversation_id}/skills`` instead,
- which provides skill information including triggers and content for V1 conversations.
- """
- try:
- # Get the agent session for this conversation
- agent_session = conversation_manager.get_agent_session(conversation.sid)
-
- if not agent_session:
- return JSONResponse(
- status_code=status.HTTP_404_NOT_FOUND,
- content={'error': 'Agent session not found for this conversation'},
- )
-
- # Access the memory to get the microagents
- memory: Memory | None = agent_session.memory
- if memory is None:
- return JSONResponse(
- status_code=status.HTTP_404_NOT_FOUND,
- content={
- 'error': 'Memory is not yet initialized for this conversation'
- },
- )
-
- # Prepare the response
- microagents = []
-
- # Add repo microagents
- for name, r_agent in memory.repo_microagents.items():
- microagents.append(
- MicroagentResponse(
- name=name,
- type='repo',
- content=r_agent.content,
- triggers=[],
- inputs=r_agent.metadata.inputs,
- tools=(
- list(r_agent.metadata.mcp_tools.mcpServers.keys())
- if r_agent.metadata.mcp_tools
- else []
- ),
- )
- )
-
- # Add knowledge microagents
- for name, k_agent in memory.knowledge_microagents.items():
- microagents.append(
- MicroagentResponse(
- name=name,
- type='knowledge',
- content=k_agent.content,
- triggers=k_agent.triggers,
- inputs=k_agent.metadata.inputs,
- tools=(
- list(k_agent.metadata.mcp_tools.mcpServers.keys())
- if k_agent.metadata.mcp_tools
- else []
- ),
- )
- )
-
- return JSONResponse(
- status_code=status.HTTP_200_OK,
- content={'microagents': [m.model_dump() for m in microagents]},
- )
- except Exception as e:
- logger.error(f'Error getting microagents: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error getting microagents: {e}'},
- )
diff --git a/openhands/server/routes/feedback.py b/openhands/server/routes/feedback.py
deleted file mode 100644
index 8a02439047..0000000000
--- a/openhands/server/routes/feedback.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from fastapi import APIRouter, Depends, Request, status
-from fastapi.responses import JSONResponse
-
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.async_event_store_wrapper import AsyncEventStoreWrapper
-from openhands.events.event_filter import EventFilter
-from openhands.events.serialization import event_to_dict
-from openhands.server.data_models.feedback import FeedbackDataModel, store_feedback
-from openhands.server.session.conversation import ServerConversation
-from openhands.server.utils import get_conversation
-from openhands.utils.async_utils import call_sync_from_async
-
-app = APIRouter(
- prefix='/api/conversations/{conversation_id}', dependencies=get_dependencies()
-)
-
-
[email protected]('/submit-feedback', deprecated=True)
-async def submit_feedback(
- request: Request, conversation: ServerConversation = Depends(get_conversation)
-) -> JSONResponse:
- """Submit user feedback.
-
- This function stores the provided feedback data.
-
- .. deprecated::
- Submitting feedback in OSS doesn't really make sense. This endpoint is deprecated
- and will be removed.
-
- To submit feedback:
- ```sh
- curl -X POST -d '{"email": "[email protected]"}' -H "Authorization:"
- ```
-
- Args:
- request (Request): The incoming request object.
- feedback (FeedbackDataModel): The feedback data to be stored.
-
- Returns:
- dict: The stored feedback data.
-
- Raises:
- HTTPException: If there's an error submitting the feedback.
- """
- # Assuming the storage service is already configured in the backend
- # and there is a function to handle the storage.
- body = await request.json()
- async_store = AsyncEventStoreWrapper(
- conversation.event_stream, filter=EventFilter(exclude_hidden=True)
- )
- trajectory = []
- async for event in async_store:
- trajectory.append(event_to_dict(event))
- feedback = FeedbackDataModel(
- email=body.get('email', ''),
- version=body.get('version', ''),
- permissions=body.get('permissions', 'private'),
- polarity=body.get('polarity', ''),
- feedback=body.get('polarity', ''),
- trajectory=trajectory,
- )
- try:
- feedback_data = await call_sync_from_async(store_feedback, feedback)
- return JSONResponse(status_code=status.HTTP_200_OK, content=feedback_data)
- except Exception as e:
- logger.error(f'Error submitting feedback: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': 'Failed to submit feedback'},
- )
diff --git a/openhands/server/routes/files.py b/openhands/server/routes/files.py
deleted file mode 100644
index bbe17ef769..0000000000
--- a/openhands/server/routes/files.py
+++ /dev/null
@@ -1,393 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import os
-from typing import Any
-
-import httpx
-from fastapi import APIRouter, Depends, HTTPException, UploadFile, status
-from fastapi.responses import FileResponse, JSONResponse
-from starlette.background import BackgroundTask
-
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.core.exceptions import AgentRuntimeUnavailableError
-from openhands.core.logger import openhands_logger as logger
-from openhands.runtime.base import Runtime
-from openhands.server.file_config import FILES_TO_IGNORE
-from openhands.server.files import POSTUploadFilesModel
-from openhands.server.session.conversation import ServerConversation
-from openhands.server.shared import conversation_manager
-from openhands.server.user_auth import get_user_id
-from openhands.server.utils import (
- get_conversation,
- get_conversation_metadata,
- get_conversation_store,
-)
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.conversation_metadata import ConversationMetadata
-from openhands.utils.async_utils import call_sync_from_async
-
-app = APIRouter(
- prefix='/api/conversations/{conversation_id}', dependencies=get_dependencies()
-)
-
-
- '/list-files',
- response_model=list[str],
- responses={
- 404: {'description': 'Runtime not initialized', 'model': dict},
- 500: {'description': 'Error listing or filtering files', 'model': dict},
- },
- deprecated=True,
-)
-async def list_files(
- metadata: ConversationMetadata = Depends(get_conversation_metadata),
- path: str | None = None,
-) -> list[str] | JSONResponse:
- """List files in the specified path.
-
- This function retrieves a list of files from the agent's runtime file store,
- excluding certain system and hidden files/directories.
-
- To list files:
- ```sh
- curl http://localhost:3000/api/conversations/{conversation_id}/list-files
- ```
-
- Args:
- metadata: The conversation metadata (provides conversation_id and user access validation).
- path (str, optional): The path to list files from. Defaults to None.
-
- Returns:
- list: A list of file names in the specified path.
-
- Raises:
- HTTPException: If there's an error listing the files.
-
- For V1 conversations, file operations are handled through the agent server.
- Use the sandbox's exposed agent server URL to access file operations.
- """
- conversation_id = metadata.conversation_id
- try:
- file_list = await conversation_manager.list_files(conversation_id, path)
- except ValueError as e:
- logger.error(f'Error listing files: {e}')
- return JSONResponse(
- status_code=status.HTTP_404_NOT_FOUND,
- content={'error': str(e)},
- )
- except AgentRuntimeUnavailableError as e:
- logger.error(f'Error listing files: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error listing files: {e}'},
- )
- except httpx.TimeoutException:
- logger.error(f'Timeout listing files for conversation {conversation_id}')
- return JSONResponse(
- status_code=status.HTTP_504_GATEWAY_TIMEOUT,
- content={'error': 'Request to runtime timed out'},
- )
- except httpx.ConnectError:
- logger.error(
- f'Connection error listing files for conversation {conversation_id}'
- )
- return JSONResponse(
- status_code=status.HTTP_502_BAD_GATEWAY,
- content={'error': 'Unable to connect to runtime'},
- )
- except httpx.HTTPStatusError as e:
- logger.error(f'HTTP error listing files: {e.response.status_code}')
- return JSONResponse(
- status_code=e.response.status_code,
- content={'error': f'Runtime returned error: {e.response.status_code}'},
- )
- except Exception as e:
- logger.error(f'Error listing files: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error listing files: {e}'},
- )
-
- file_list = [f for f in file_list if f not in FILES_TO_IGNORE]
-
- return file_list
-
-
-# NOTE: We use response_model=None for endpoints that can return multiple response types
-# (like FileResponse | JSONResponse). This is because FastAPI's response_model expects a
-# Pydantic model, but Starlette response classes like FileResponse are not Pydantic models.
-# Instead, we document the possible responses using the 'responses' parameter and maintain
-# proper type annotations for mypy.
- '/select-file',
- response_model=None,
- responses={
- 200: {'description': 'File content returned as JSON', 'model': dict[str, str]},
- 500: {'description': 'Error opening file', 'model': dict},
- 415: {'description': 'Unsupported media type', 'model': dict},
- },
- deprecated=True,
-)
-async def select_file(
- file: str,
- metadata: ConversationMetadata = Depends(get_conversation_metadata),
-) -> FileResponse | JSONResponse:
- """Retrieve the content of a specified file.
-
- To select a file:
- ```sh
- curl http://localhost:3000/api/conversations/{conversation_id}/select-file?file=<file_path>
- ```
-
- Args:
- file (str): The path of the file to be retrieved (relative to workspace root).
- metadata: The conversation metadata (provides conversation_id and user access validation).
-
- Returns:
- dict: A dictionary containing the file content.
-
- Raises:
- HTTPException: If there's an error opening the file.
-
- For V1 conversations, file operations are handled through the agent server.
- Use the sandbox's exposed agent server URL to access file operations.
- """
- conversation_id = metadata.conversation_id
- try:
- content, error = await conversation_manager.select_file(conversation_id, file)
- except ValueError as e:
- logger.error(f'Error opening file {file}: {e}')
- return JSONResponse(
- status_code=status.HTTP_404_NOT_FOUND,
- content={'error': str(e)},
- )
- except AgentRuntimeUnavailableError as e:
- logger.error(f'Error opening file {file}: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error opening file: {e}'},
- )
- except httpx.TimeoutException:
- logger.error(f'Timeout reading file for conversation {conversation_id}')
- return JSONResponse(
- status_code=status.HTTP_504_GATEWAY_TIMEOUT,
- content={'error': 'Request to runtime timed out'},
- )
- except httpx.ConnectError:
- logger.error(
- f'Connection error reading file for conversation {conversation_id}'
- )
- return JSONResponse(
- status_code=status.HTTP_502_BAD_GATEWAY,
- content={'error': 'Unable to connect to runtime'},
- )
- except Exception as e:
- logger.error(f'Error opening file {file}: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error opening file: {e}'},
- )
-
- if content is not None:
- return JSONResponse(content={'code': content})
- elif error and error.startswith('BINARY_FILE:'):
- return JSONResponse(
- status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
- content={'error': f'Unable to open binary file: {file}'},
- )
- else:
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error opening file: {error}'},
- )
-
-
- '/zip-directory',
- response_model=None,
- responses={
- 200: {'description': 'Zipped workspace returned as FileResponse'},
- 500: {'description': 'Error zipping workspace', 'model': dict},
- },
- deprecated=True,
-)
-def zip_current_workspace(
- conversation: ServerConversation = Depends(get_conversation),
-) -> FileResponse | JSONResponse:
- """Download the current workspace as a zip file.
-
- For V1 conversations, file operations are handled through the agent server.
- Use the sandbox's exposed agent server URL to access file operations.
- """
- try:
- logger.debug('Zipping workspace')
- runtime: Runtime = conversation.runtime
- path = runtime.config.workspace_mount_path_in_sandbox
- try:
- zip_file_path = runtime.copy_from(path)
- except AgentRuntimeUnavailableError as e:
- logger.error(f'Error zipping workspace: {e}')
- return JSONResponse(
- status_code=500,
- content={'error': f'Error zipping workspace: {e}'},
- )
- return FileResponse(
- path=zip_file_path,
- filename='workspace.zip',
- media_type='application/zip',
- background=BackgroundTask(lambda: os.unlink(zip_file_path)),
- )
- except Exception as e:
- logger.error(f'Error zipping workspace: {e}')
- raise HTTPException(
- status_code=500,
- detail='Failed to zip workspace',
- )
-
-
- '/git/changes',
- response_model=list[dict[str, str]],
- responses={
- 404: {'description': 'Not a git repository', 'model': dict},
- 500: {'description': 'Error getting changes', 'model': dict},
- },
- deprecated=True,
-)
-async def git_changes(
- conversation: ServerConversation = Depends(get_conversation),
- conversation_store: ConversationStore = Depends(get_conversation_store),
- user_id: str = Depends(get_user_id),
-) -> list[dict[str, str]] | JSONResponse:
- """Get git changes in the workspace.
-
- For V1 conversations, git operations are handled through the agent server.
- Use the sandbox's exposed agent server URL to access git operations.
- """
- runtime: Runtime = conversation.runtime
-
- cwd = runtime.config.workspace_mount_path_in_sandbox
- logger.info(f'Getting git changes in {cwd}')
-
- try:
- changes = await call_sync_from_async(runtime.get_git_changes, cwd)
- if changes is None:
- return JSONResponse(
- status_code=404,
- content={'error': 'Not a git repository'},
- )
- return changes
- except AgentRuntimeUnavailableError as e:
- logger.error(f'Runtime unavailable: {e}')
- return JSONResponse(
- status_code=500,
- content={'error': f'Error getting changes: {e}'},
- )
- except Exception as e:
- logger.error(f'Error getting changes: {e}')
- return JSONResponse(
- status_code=500,
- content={'error': str(e)},
- )
-
-
- '/git/diff',
- response_model=dict[str, Any],
- responses={500: {'description': 'Error getting diff', 'model': dict}},
- deprecated=True,
-)
-async def git_diff(
- path: str,
- conversation_store: Any = Depends(get_conversation_store),
- conversation: ServerConversation = Depends(get_conversation),
-) -> dict[str, Any] | JSONResponse:
- """Get git diff for a specific file.
-
- For V1 conversations, git operations are handled through the agent server.
- Use the sandbox's exposed agent server URL to access git operations.
- """
- runtime: Runtime = conversation.runtime
-
- cwd = runtime.config.workspace_mount_path_in_sandbox
-
- try:
- diff = await call_sync_from_async(runtime.get_git_diff, path, cwd)
- return diff
- except AgentRuntimeUnavailableError as e:
- logger.error(f'Error getting diff: {e}')
- return JSONResponse(
- status_code=500,
- content={'error': f'Error getting diff: {e}'},
- )
-
-
[email protected]('/upload-files', response_model=POSTUploadFilesModel, deprecated=True)
-async def upload_files(
- files: list[UploadFile],
- metadata: ConversationMetadata = Depends(get_conversation_metadata),
-):
- """Upload files to the workspace.
-
- For V1 conversations, file operations are handled through the agent server.
- Use the sandbox's exposed agent server URL to access file operations.
- """
- conversation_id = metadata.conversation_id
-
- # Read all file contents
- file_data: list[tuple[str, bytes]] = []
- for file in files:
- content = await file.read()
- file_data.append((str(file.filename), content))
-
- try:
- uploaded_files, skipped_files = await conversation_manager.upload_files(
- conversation_id, file_data
- )
- except ValueError as e:
- logger.error(f'Error uploading files: {e}')
- return JSONResponse(
- status_code=status.HTTP_404_NOT_FOUND,
- content={'error': str(e)},
- )
- except httpx.TimeoutException:
- logger.error(f'Timeout uploading files for conversation {conversation_id}')
- return JSONResponse(
- status_code=status.HTTP_504_GATEWAY_TIMEOUT,
- content={'error': 'Request to runtime timed out'},
- )
- except httpx.ConnectError:
- logger.error(
- f'Connection error uploading files for conversation {conversation_id}'
- )
- return JSONResponse(
- status_code=status.HTTP_502_BAD_GATEWAY,
- content={'error': 'Unable to connect to runtime'},
- )
- except httpx.HTTPStatusError as e:
- logger.error(f'HTTP error uploading files: {e.response.status_code}')
- return JSONResponse(
- status_code=e.response.status_code,
- content={'error': f'Runtime returned error: {e.response.status_code}'},
- )
- except Exception as e:
- logger.error(f'Error uploading files: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error uploading files: {e}'},
- )
-
- return JSONResponse(
- status_code=status.HTTP_200_OK,
- content={
- 'uploaded_files': uploaded_files,
- 'skipped_files': skipped_files,
- },
- )
diff --git a/openhands/server/routes/git.py b/openhands/server/routes/git.py
deleted file mode 100644
index 9d40090428..0000000000
--- a/openhands/server/routes/git.py
+++ /dev/null
@@ -1,465 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from types import MappingProxyType
-from typing import Annotated, cast
-
-from fastapi import APIRouter, Depends, Query, status
-from fastapi.responses import JSONResponse
-from pydantic import SecretStr
-
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.core.logger import openhands_logger as logger
-from openhands.integrations.provider import (
- PROVIDER_TOKEN_TYPE,
- ProviderHandler,
-)
-from openhands.integrations.service_types import (
- AuthenticationError,
- Branch,
- PaginatedBranchesResponse,
- ProviderType,
- Repository,
- SuggestedTask,
- UnknownException,
- User,
-)
-from openhands.microagent.types import (
- MicroagentContentResponse,
- MicroagentResponse,
-)
-from openhands.server.shared import server_config
-from openhands.server.user_auth import (
- get_access_token,
- get_provider_tokens,
- get_user_id,
-)
-
-app = APIRouter(prefix='/api/user', dependencies=get_dependencies())
-
-
- '/installations',
- response_model=list[str],
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/installations/search` instead.',
-)
-async def get_user_installations(
- provider: ProviderType,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-):
- if provider_tokens:
- client = ProviderHandler(
- provider_tokens=provider_tokens,
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
-
- if provider == ProviderType.GITHUB:
- return await client.get_github_installations()
- elif provider == ProviderType.BITBUCKET:
- return await client.get_bitbucket_workspaces()
- elif provider == ProviderType.BITBUCKET_DATA_CENTER:
- return await client.get_bitbucket_dc_projects()
- elif provider == ProviderType.AZURE_DEVOPS:
- return await client.get_azure_devops_organizations()
- else:
- return JSONResponse(
- content=f"Provider {provider} doesn't support installations",
- status_code=status.HTTP_400_BAD_REQUEST,
- )
-
- raise AuthenticationError('Git provider token required. (such as GitHub).')
-
-
- '/repositories',
- response_model=list[Repository],
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/repositories/search` instead.',
-)
-async def get_user_repositories(
- sort: str = 'pushed',
- selected_provider: Annotated[ProviderType | None, Query()] = None,
- page: int | None = None,
- per_page: int | None = None,
- installation_id: str | None = None,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[Repository] | JSONResponse:
- if provider_tokens:
- client = ProviderHandler(
- provider_tokens=provider_tokens,
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
- try:
- return await client.get_repositories(
- sort,
- server_config.app_mode,
- selected_provider,
- page,
- per_page,
- installation_id,
- )
-
- except UnknownException as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- logger.info(
- f'Returning 401 Unauthorized - Git provider token required for user_id: {user_id}'
- )
- raise AuthenticationError('Git provider token required. (such as GitHub).')
-
-
[email protected]('/info', response_model=User, deprecated=True)
-async def get_user(
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> User | JSONResponse:
- """Get the current user git info. Use GET /api/v1/users/git-info instead"""
- if provider_tokens:
- client = ProviderHandler(
- provider_tokens=provider_tokens, external_auth_token=access_token
- )
-
- try:
- user: User = await client.get_user()
- return user
-
- except UnknownException as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- logger.info(
- f'Returning 401 Unauthorized - Git provider token required for user_id: {user_id}'
- )
- raise AuthenticationError('Git provider token required. (such as GitHub).')
-
-
- '/search/repositories',
- response_model=list[Repository],
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/repositories/search` instead.',
-)
-async def search_repositories(
- query: str,
- per_page: int = 5,
- sort: str = 'stars',
- order: str = 'desc',
- selected_provider: Annotated[ProviderType | None, Query()] = None,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[Repository] | JSONResponse:
- if provider_tokens:
- client = ProviderHandler(
- provider_tokens=provider_tokens,
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
- try:
- repos: list[Repository] = await client.search_repositories(
- selected_provider, query, per_page, sort, order, server_config.app_mode
- )
- return repos
-
- except UnknownException as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- logger.info(
- f'Returning 401 Unauthorized - Git provider token required for user_id: {user_id}'
- )
- raise AuthenticationError('Git provider token required.')
-
-
- '/search/branches',
- response_model=list[Branch],
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/branches/search` instead.',
-)
-async def search_branches(
- repository: str,
- query: str,
- per_page: int = 30,
- selected_provider: Annotated[ProviderType | None, Query()] = None,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[Branch] | JSONResponse:
- if provider_tokens:
- client = ProviderHandler(
- provider_tokens=provider_tokens,
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
- try:
- branches: list[Branch] = await client.search_branches(
- selected_provider, repository, query, per_page
- )
- return branches
-
- except AuthenticationError as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_401_UNAUTHORIZED,
- )
-
- except UnknownException as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- logger.info(
- f'Returning 401 Unauthorized - Git provider token required for user_id: {user_id}'
- )
- return JSONResponse(
- content='Git provider token required.',
- status_code=status.HTTP_401_UNAUTHORIZED,
- )
-
-
- '/suggested-tasks',
- response_model=list[SuggestedTask],
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/suggested-tasks/search` instead.',
-)
-async def get_suggested_tasks(
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[SuggestedTask] | JSONResponse:
- """Get suggested tasks for the authenticated user across their most recently pushed repositories.
-
- Returns:
- - PRs owned by the user
- - Issues assigned to the user.
- """
- if provider_tokens:
- client = ProviderHandler(
- provider_tokens=provider_tokens, external_auth_token=access_token
- )
- try:
- tasks: list[SuggestedTask] = await client.get_suggested_tasks()
- return tasks
-
- except UnknownException as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
- logger.info(f'Returning 401 Unauthorized - No providers set for user_id: {user_id}')
- raise AuthenticationError('No providers set.')
-
-
- '/repository/branches',
- response_model=PaginatedBranchesResponse,
- deprecated=True,
- description='Deprecated: Use `/api/v1/git/branches/search` instead.',
-)
-async def get_repository_branches(
- repository: str,
- page: int = 1,
- per_page: int = 30,
- selected_provider: Annotated[ProviderType | None, Query()] = None,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> PaginatedBranchesResponse | JSONResponse:
- """Get branches for a repository.
-
- Args:
- repository: The repository name in the format 'owner/repo'
- page: Page number for pagination (default: 1)
- per_page: Number of branches per page (default: 30)
- selected_provider: Optional provider hint to avoid trying other providers
-
- Returns:
- A paginated response with branches for the repository
- """
- if provider_tokens:
- client = ProviderHandler(
- provider_tokens=provider_tokens, external_auth_token=access_token
- )
- try:
- branches_response: PaginatedBranchesResponse = await client.get_branches(
- repository,
- specified_provider=selected_provider,
- page=page,
- per_page=per_page,
- )
- return branches_response
-
- except UnknownException as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- logger.info(
- f'Returning 401 Unauthorized - Git provider token required for user_id: {user_id}'
- )
- raise AuthenticationError('Git provider token required. (such as GitHub).')
-
-
- '/repository/{repository_name:path}/microagents',
- response_model=list[MicroagentResponse],
- deprecated=True,
-)
-async def get_repository_microagents(
- repository_name: str,
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> list[MicroagentResponse] | JSONResponse:
- """Scan the microagents directory of a repository and return the list of microagents.
-
- .. deprecated::
- This endpoint is deprecated. The microagents UI has already been removed
- and is not supported in V1.
-
- The microagents directory location depends on the git provider and actual repository name:
- - If git provider is not GitLab and actual repository name is ".openhands": scans "microagents" folder
- - If git provider is GitLab and actual repository name is "openhands-config": scans "microagents" folder
- - Otherwise: scans ".openhands/microagents" folder
-
- Note: This API returns microagent metadata without content for performance.
- Use the separate content API to fetch individual microagent content.
-
- Args:
- repository_name: Repository name in the format 'owner/repo' or 'domain/owner/repo'
- provider_tokens: Provider tokens for authentication
- access_token: Access token for external authentication
- user_id: User ID for authentication
-
- Returns:
- List of microagents found in the repository's microagents directory (without content)
- """
- try:
- # Create provider handler for API authentication
- provider_handler = ProviderHandler(
- provider_tokens=provider_tokens
- or cast(PROVIDER_TOKEN_TYPE, MappingProxyType({})),
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
-
- # Fetch microagents using the provider handler
- microagents = await provider_handler.get_microagents(repository_name)
-
- logger.info(f'Found {len(microagents)} microagents in {repository_name}')
- return microagents
-
- except AuthenticationError:
- raise
-
- except RuntimeError as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- except Exception as e:
- logger.error(
- f'Error scanning repository {repository_name}: {str(e)}', exc_info=True
- )
- return JSONResponse(
- content=f'Error scanning repository: {str(e)}',
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
-
- '/repository/{repository_name:path}/microagents/content',
- response_model=MicroagentContentResponse,
- deprecated=True,
-)
-async def get_repository_microagent_content(
- repository_name: str,
- file_path: str = Query(
- ..., description='Path to the microagent file within the repository'
- ),
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- access_token: SecretStr | None = Depends(get_access_token),
- user_id: str | None = Depends(get_user_id),
-) -> MicroagentContentResponse | JSONResponse:
- """Fetch the content of a specific microagent file from a repository.
-
- .. deprecated::
- This endpoint is deprecated. The microagents UI has already been removed
- and is not supported in V1.
-
- Args:
- repository_name: Repository name in the format 'owner/repo' or 'domain/owner/repo'
- file_path: Query parameter - Path to the microagent file within the repository
- provider_tokens: Provider tokens for authentication
- access_token: Access token for external authentication
- user_id: User ID for authentication
-
- Returns:
- Microagent file content and metadata
-
- Example:
- GET /api/user/repository/owner/repo/microagents/content?file_path=.openhands/microagents/my-agent.md
- """
- try:
- # Create provider handler for API authentication
- provider_handler = ProviderHandler(
- provider_tokens=provider_tokens
- or cast(PROVIDER_TOKEN_TYPE, MappingProxyType({})),
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
-
- # Fetch file content using the provider handler
- response = await provider_handler.get_microagent_content(
- repository_name, file_path
- )
-
- logger.info(
- f'Retrieved content for microagent {file_path} from {repository_name}'
- )
-
- return response
-
- except AuthenticationError:
- raise
-
- except RuntimeError as e:
- return JSONResponse(
- content=str(e),
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- except Exception as e:
- logger.error(
- f'Error fetching microagent content from {repository_name}/{file_path}: {str(e)}',
- exc_info=True,
- )
- return JSONResponse(
- content=f'Error fetching microagent content: {str(e)}',
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
diff --git a/openhands/server/routes/manage_conversations.py b/openhands/server/routes/manage_conversations.py
deleted file mode 100644
index 838084f2e9..0000000000
--- a/openhands/server/routes/manage_conversations.py
+++ /dev/null
@@ -1,1617 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import asyncio
-import base64
-import itertools
-import json
-import os
-import re
-import uuid
-from datetime import datetime, timedelta, timezone
-from typing import Annotated
-from urllib.parse import urlparse
-
-import base62
-import httpx
-from fastapi import APIRouter, Depends, Query, Request, status
-from fastapi.responses import JSONResponse
-from jinja2 import Environment, FileSystemLoader
-from pydantic import BaseModel, ConfigDict, Field, SecretStr
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from openhands.app_server.app_conversation.app_conversation_info_service import (
- AppConversationInfoService,
-)
-from openhands.app_server.app_conversation.app_conversation_models import (
- AppConversation,
-)
-from openhands.app_server.app_conversation.app_conversation_service import (
- AppConversationService,
-)
-from openhands.app_server.config import (
- depends_app_conversation_info_service,
- depends_app_conversation_service,
- depends_db_session,
- depends_httpx_client,
- depends_sandbox_service,
-)
-from openhands.app_server.sandbox.sandbox_models import AGENT_SERVER, SandboxStatus
-from openhands.app_server.sandbox.sandbox_service import SandboxService
-from openhands.app_server.services.db_session_injector import set_db_session_keep_open
-from openhands.app_server.services.httpx_client_injector import (
- set_httpx_client_keep_open,
-)
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.core.config.llm_config import LLMConfig
-from openhands.core.config.mcp_config import MCPConfig
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.action import (
- ChangeAgentStateAction,
- NullAction,
-)
-from openhands.events.event_filter import EventFilter
-from openhands.events.event_store import EventStore
-from openhands.events.observation import (
- AgentStateChangedObservation,
- NullObservation,
-)
-from openhands.integrations.provider import (
- PROVIDER_TOKEN_TYPE,
- ProviderHandler,
-)
-from openhands.integrations.service_types import (
- CreateMicroagent,
- ProviderType,
- SuggestedTask,
-)
-from openhands.runtime import get_runtime_cls
-from openhands.runtime.runtime_status import RuntimeStatus
-from openhands.sdk.conversation import ConversationExecutionStatus
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.data_models.conversation_info import ConversationInfo
-from openhands.server.data_models.conversation_info_result_set import (
- ConversationInfoResultSet,
-)
-from openhands.server.services.conversation_service import (
- create_new_conversation,
- setup_init_conversation_settings,
-)
-from openhands.server.shared import (
- ConversationStoreImpl,
- config,
- conversation_manager,
- file_store,
-)
-from openhands.server.types import LLMAuthenticationError, MissingSettingsError
-from openhands.server.user_auth import (
- get_auth_type,
- get_provider_tokens,
- get_secrets,
- get_user_id,
- get_user_settings,
- get_user_settings_store,
-)
-from openhands.server.user_auth.user_auth import AuthType
-from openhands.server.utils import get_conversation as get_conversation_metadata
-from openhands.server.utils import get_conversation_store, validate_conversation_id
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.conversation_metadata import (
- ConversationMetadata,
- ConversationTrigger,
-)
-from openhands.storage.data_models.conversation_status import ConversationStatus
-from openhands.storage.data_models.secrets import Secrets
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.settings.settings_store import SettingsStore
-from openhands.utils.async_utils import wait_all
-from openhands.utils.conversation_summary import get_default_conversation_title
-from openhands.utils.environment import get_effective_llm_base_url
-
-app = APIRouter(prefix='/api', dependencies=get_dependencies())
-app_conversation_service_dependency = depends_app_conversation_service()
-app_conversation_info_service_dependency = depends_app_conversation_info_service()
-sandbox_service_dependency = depends_sandbox_service()
-db_session_dependency = depends_db_session()
-httpx_client_dependency = depends_httpx_client()
-_RESUME_GRACE_PERIOD = 60
-
-
-def _filter_conversations_by_age(
- conversations: list[ConversationMetadata], max_age_seconds: int
-) -> list:
- """Filter conversations by age, removing those older than max_age_seconds.
-
- Args:
- conversations: List of conversations to filter
- max_age_seconds: Maximum age in seconds for conversations to be included
-
- Returns:
- List of conversations that meet the age criteria
- """
- now = datetime.now(timezone.utc)
- filtered_results = []
-
- for conversation in conversations:
- # Skip conversations without created_at or older than max_age
- if not hasattr(conversation, 'created_at'):
- continue
-
- age_seconds = (
- now - conversation.created_at.replace(tzinfo=timezone.utc)
- ).total_seconds()
- if age_seconds > max_age_seconds:
- continue
-
- filtered_results.append(conversation)
-
- return filtered_results
-
-
-async def _build_conversation_result_set(
- filtered_conversations: list, next_page_id: str | None
-) -> ConversationInfoResultSet:
- """Build a ConversationInfoResultSet from filtered conversations.
-
- This function handles the common logic of getting conversation IDs, connections,
- agent loop info, and building the final result set.
-
- Args:
- filtered_conversations: List of filtered conversations
- next_page_id: Next page ID for pagination
-
- Returns:
- ConversationInfoResultSet with the processed conversations
- """
- conversation_ids = set(
- conversation.conversation_id for conversation in filtered_conversations
- )
- connection_ids_to_conversation_ids = await conversation_manager.get_connections(
- filter_to_sids=conversation_ids
- )
- agent_loop_info = await conversation_manager.get_agent_loop_info(
- filter_to_sids=conversation_ids
- )
- agent_loop_info_by_conversation_id = {
- info.conversation_id: info for info in agent_loop_info
- }
-
- result = ConversationInfoResultSet(
- results=await wait_all(
- _get_conversation_info(
- conversation=conversation,
- num_connections=sum(
- 1
- for conversation_id in connection_ids_to_conversation_ids.values()
- if conversation_id == conversation.conversation_id
- ),
- agent_loop_info=agent_loop_info_by_conversation_id.get(
- conversation.conversation_id
- ),
- )
- for conversation in filtered_conversations
- ),
- next_page_id=next_page_id,
- )
- return result
-
-
-class InitSessionRequest(BaseModel):
- repository: str | None = None
- git_provider: ProviderType | None = None
- selected_branch: str | None = None
- initial_user_msg: str | None = None
- image_urls: list[str] | None = None
- replay_json: str | None = None
- suggested_task: SuggestedTask | None = None
- create_microagent: CreateMicroagent | None = None
- conversation_instructions: str | None = None
- mcp_config: MCPConfig | None = None
- # Only nested runtimes require the ability to specify a conversation id, and it could be a security risk
- if os.getenv('ALLOW_SET_CONVERSATION_ID', '0') == '1':
- conversation_id: str = Field(default_factory=lambda: uuid.uuid4().hex)
-
- model_config = ConfigDict(extra='forbid')
-
-
-class ConversationResponse(BaseModel):
- status: str
- conversation_id: str
- message: str | None = None
- conversation_status: ConversationStatus | None = None
-
-
-class ProvidersSetModel(BaseModel):
- providers_set: list[ProviderType] | None = None
-
-
[email protected]('/conversations', deprecated=True)
-async def new_conversation(
- data: InitSessionRequest,
- user_id: str = Depends(get_user_id),
- provider_tokens: PROVIDER_TOKEN_TYPE = Depends(get_provider_tokens),
- user_secrets: Secrets = Depends(get_secrets),
- auth_type: AuthType | None = Depends(get_auth_type),
-) -> ConversationResponse:
- """Initialize a new session or join an existing one.
-
- After successful initialization, the client should connect to the WebSocket
- using the returned conversation ID.
-
- Use the V1 endpoint ``POST /api/v1/app-conversations`` instead, which provides
- improved conversation management with sandbox lifecycle support.
- """
- logger.info(f'initializing_new_conversation:{data}')
- repository = data.repository
- selected_branch = data.selected_branch
- initial_user_msg = data.initial_user_msg
- image_urls = data.image_urls or []
- replay_json = data.replay_json
- suggested_task = data.suggested_task
- create_microagent = data.create_microagent
- git_provider = data.git_provider
- conversation_instructions = data.conversation_instructions
-
- conversation_trigger = ConversationTrigger.GUI
-
- if suggested_task:
- initial_user_msg = suggested_task.get_prompt_for_task()
- conversation_trigger = ConversationTrigger.SUGGESTED_TASK
- elif create_microagent:
- conversation_trigger = ConversationTrigger.MICROAGENT_MANAGEMENT
- # Set repository and git_provider from create_microagent if not already set
- if not repository and create_microagent.repo:
- repository = create_microagent.repo
- if not git_provider and create_microagent.git_provider:
- git_provider = create_microagent.git_provider
-
- if auth_type == AuthType.BEARER:
- conversation_trigger = ConversationTrigger.REMOTE_API_KEY
-
- try:
- if repository:
- provider_handler = ProviderHandler(provider_tokens)
- # Check against git_provider, otherwise check all provider apis
- await provider_handler.verify_repo_provider(repository, git_provider)
-
- conversation_id = getattr(data, 'conversation_id', None) or uuid.uuid4().hex
- agent_loop_info = await create_new_conversation(
- user_id=user_id,
- git_provider_tokens=provider_tokens,
- custom_secrets=user_secrets.custom_secrets if user_secrets else None,
- selected_repository=repository,
- selected_branch=selected_branch,
- initial_user_msg=initial_user_msg,
- image_urls=image_urls,
- replay_json=replay_json,
- conversation_trigger=conversation_trigger,
- conversation_instructions=conversation_instructions,
- git_provider=git_provider,
- conversation_id=conversation_id,
- mcp_config=data.mcp_config,
- )
-
- return ConversationResponse(
- status='ok',
- conversation_id=conversation_id,
- conversation_status=agent_loop_info.status,
- )
- except MissingSettingsError as e:
- return JSONResponse(
- content={
- 'status': 'error',
- 'message': str(e),
- 'msg_id': 'CONFIGURATION$SETTINGS_NOT_FOUND',
- },
- status_code=status.HTTP_400_BAD_REQUEST,
- )
-
- except LLMAuthenticationError as e:
- return JSONResponse(
- content={
- 'status': 'error',
- 'message': str(e),
- 'msg_id': RuntimeStatus.ERROR_LLM_AUTHENTICATION.value,
- },
- status_code=status.HTTP_400_BAD_REQUEST,
- )
-
-
[email protected]('/conversations', deprecated=True)
-async def search_conversations(
- page_id: str | None = None,
- limit: int = 20,
- selected_repository: str | None = None,
- conversation_trigger: ConversationTrigger | None = None,
- include_sub_conversations: Annotated[
- bool,
- Query(
- title='If True, include sub-conversations in the results. If False (default), exclude all sub-conversations.'
- ),
- ] = False,
- conversation_store: ConversationStore = Depends(get_conversation_store),
- app_conversation_service: AppConversationService = app_conversation_service_dependency,
-) -> ConversationInfoResultSet:
- """Search and list conversations with pagination support.
-
- Use the V1 endpoint ``GET /api/v1/app-conversations/search`` instead, which provides
- enhanced filtering, sorting, and pagination capabilities.
- """
- # Parse combined page_id to extract separate page_ids for each source
- v0_page_id = None
- v1_page_id = None
-
- if page_id:
- try:
- # Try to parse as JSON first
- page_data = json.loads(base64.b64decode(page_id))
- v0_page_id = page_data.get('v0')
- v1_page_id = page_data.get('v1')
- except (json.JSONDecodeError, TypeError):
- # Fallback: treat as v0 page_id for backward compatibility
- v0_page_id = page_id
-
- # Get results from old conversation store (V0)
- conversation_metadata_result_set = await conversation_store.search(
- v0_page_id, limit
- )
-
- # Get results from new app conversation service (V1)
- age_filter_date = None
- if config.conversation_max_age_seconds:
- age_filter_date = datetime.now(timezone.utc) - timedelta(
- seconds=config.conversation_max_age_seconds
- )
-
- app_conversation_page = await app_conversation_service.search_app_conversations(
- page_id=v1_page_id,
- limit=limit,
- # Apply age filter at the service level if possible
- created_at__gte=age_filter_date,
- include_sub_conversations=include_sub_conversations,
- )
-
- # Convert V1 conversations to ConversationInfo format
- v1_conversations = [
- _to_conversation_info(app_conv) for app_conv in app_conversation_page.items
- ]
-
- # Apply age filter to V0 conversations
- v0_filtered_results = _filter_conversations_by_age(
- conversation_metadata_result_set.results,
- config.conversation_max_age_seconds,
- )
- v0_conversation_ids = set(
- conversation.conversation_id for conversation in v0_filtered_results
- )
- await conversation_manager.get_connections(filter_to_sids=v0_conversation_ids)
- v0_agent_loop_info = await conversation_manager.get_agent_loop_info(
- filter_to_sids=v0_conversation_ids
- )
- v0_agent_loop_info_by_conversation_id = {
- info.conversation_id: info for info in v0_agent_loop_info
- }
- v0_conversations = await wait_all(
- _get_conversation_info(
- conversation=conversation,
- num_connections=sum(
- 1
- for conversation_id in v0_agent_loop_info_by_conversation_id.values()
- if conversation_id == conversation.conversation_id
- ),
- agent_loop_info=v0_agent_loop_info_by_conversation_id.get(
- conversation.conversation_id
- ),
- )
- for conversation in v0_filtered_results
- )
-
- # Apply additional filters to both V0 and V1 results
- def apply_filters(conversations: list[ConversationInfo]) -> list[ConversationInfo]:
- filtered = []
- for conversation in conversations:
- # Apply repository filter
- if (
- selected_repository is not None
- and conversation.selected_repository != selected_repository
- ):
- continue
-
- # Apply conversation trigger filter
- if (
- conversation_trigger is not None
- and conversation.trigger != conversation_trigger
- ):
- continue
-
- filtered.append(conversation)
- return filtered
-
- v0_final_filtered = apply_filters(v0_conversations)
- v1_final_filtered = apply_filters(v1_conversations)
-
- # Combine results from both sources
- all_conversations = v0_final_filtered + v1_final_filtered
-
- # Sort by created_at descending (most recent first)
- all_conversations.sort(
- key=lambda x: x.created_at or datetime.min.replace(tzinfo=timezone.utc),
- reverse=True,
- )
-
- # Limit to requested number of results
- final_results = all_conversations[:limit]
-
- # Create combined page_id for next page
- next_page_id = None
- if (
- conversation_metadata_result_set.next_page_id
- or app_conversation_page.next_page_id
- ):
- next_page_data = {
- 'v0': conversation_metadata_result_set.next_page_id,
- 'v1': app_conversation_page.next_page_id,
- }
- # Only include page_id if at least one source has more pages
- if next_page_data['v0'] or next_page_data['v1']:
- next_page_id = base64.b64encode(
- json.dumps(next_page_data).encode()
- ).decode()
-
- return ConversationInfoResultSet(results=final_results, next_page_id=next_page_id)
-
-
[email protected]('/conversations/{conversation_id}', deprecated=True)
-async def get_conversation(
- conversation_id: str = Depends(validate_conversation_id),
- conversation_store: ConversationStore = Depends(get_conversation_store),
- app_conversation_service: AppConversationService = app_conversation_service_dependency,
- httpx_client: httpx.AsyncClient = httpx_client_dependency,
-) -> ConversationInfo | None:
- """Get a single conversation by ID.
-
- Use the V1 endpoint ``GET /api/v1/app-conversations?ids={conversation_id}`` instead,
- which supports batch retrieval of conversations by their IDs.
- """
- try:
- # Shim to add V1 conversations
- try:
- conversation_uuid = uuid.UUID(conversation_id)
- app_conversation = await app_conversation_service.get_app_conversation(
- conversation_uuid
- )
- if app_conversation:
- if (
- app_conversation.sandbox_status == SandboxStatus.RUNNING
- and app_conversation.execution_status is None
- ):
- # The sandbox is running, but we were unable to determine a status for
- # the conversation. It may be that it is still starting, or that the
- # conversation has been stopped / deleted.
- try:
- # Check the server info is available
- conversation_url = urlparse(app_conversation.conversation_url)
- sandbox_info_url = f'{str(conversation_url.scheme)}://{str(conversation_url.netloc)}/server_info'
- response = await httpx_client.get(sandbox_info_url)
- response.raise_for_status()
- server_info = response.json()
-
- # If the server has not been running long, we consider it still starting
- uptime = int(server_info.get('uptime'))
- if uptime < _RESUME_GRACE_PERIOD:
- app_conversation.sandbox_status = SandboxStatus.STARTING
-
- except Exception:
- # The sandbox is marked as RUNNING, but the server is not responding.
- # There is a bug in runtime API which means that the server is marked
- # as RUNNING before it is actually started. (Primarily affecting resumed
- # runtimes) As a temporary work around for this, we mark the server as
- # STARTING. If the sandbox is actually in an error state, the API will
- # discover this quite quickly and mark the sandbox as ERROR
- logger.warning(
- 'get_sandbox_info_failed',
- extra={
- 'conversation_id': app_conversation.id,
- 'sandbox_id': app_conversation.sandbox_id,
- },
- exc_info=True,
- stack_info=True,
- )
- app_conversation.sandbox_status = SandboxStatus.STARTING
-
- return _to_conversation_info(app_conversation)
- except (ValueError, TypeError, Exception):
- # Not a V1 conversation or service error
- pass
-
- metadata = await conversation_store.get_metadata(conversation_id)
- num_connections = len(
- await conversation_manager.get_connections(filter_to_sids={conversation_id})
- )
- agent_loop_infos = await conversation_manager.get_agent_loop_info(
- filter_to_sids={conversation_id}
- )
- agent_loop_info = agent_loop_infos[0] if agent_loop_infos else None
- conversation_info = await _get_conversation_info(
- metadata, num_connections, agent_loop_info
- )
- return conversation_info
- except FileNotFoundError:
- return None
-
-
[email protected]('/conversations/{conversation_id}', deprecated=True)
-async def delete_conversation(
- request: Request,
- conversation_id: str = Depends(validate_conversation_id),
- user_id: str | None = Depends(get_user_id),
- app_conversation_service: AppConversationService = app_conversation_service_dependency,
- app_conversation_info_service: AppConversationInfoService = app_conversation_info_service_dependency,
- sandbox_service: SandboxService = sandbox_service_dependency,
- db_session: AsyncSession = db_session_dependency,
- httpx_client: httpx.AsyncClient = httpx_client_dependency,
-) -> bool:
- """Delete a conversation by ID.
-
- For V1 conversations, use ``DELETE /api/v1/sandboxes/{sandbox_id}`` to delete the
- associated sandbox, which will clean up the conversation resources.
- """
- set_db_session_keep_open(request.state, True)
- set_httpx_client_keep_open(request.state, True)
-
- # Try V1 conversation first
- v1_result = await _try_delete_v1_conversation(
- conversation_id,
- app_conversation_service,
- app_conversation_info_service,
- sandbox_service,
- db_session,
- httpx_client,
- )
- if v1_result is not None:
- return v1_result
-
- # Close connections
- await db_session.close()
- await httpx_client.aclose()
-
- # V0 conversation logic
- return await _delete_v0_conversation(conversation_id, user_id)
-
-
-async def _try_delete_v1_conversation(
- conversation_id: str,
- app_conversation_service: AppConversationService,
- app_conversation_info_service: AppConversationInfoService,
- sandbox_service: SandboxService,
- db_session: AsyncSession,
- httpx_client: httpx.AsyncClient,
-) -> bool | None:
- """Try to delete a V1 conversation. Returns None if not a V1 conversation."""
- result = None
- try:
- conversation_uuid = uuid.UUID(conversation_id)
- # Check if it's a V1 conversation by trying to get it
- app_conversation_info = (
- await app_conversation_info_service.get_app_conversation_info(
- conversation_uuid
- )
- )
- if app_conversation_info:
- # Check if the sandbox is shared with other conversations
- # (e.g. multiple conversations can share a sandbox via /new).
- # If shared, skip the agent server DELETE call to avoid
- # destabilizing the runtime for the remaining conversations.
- sandbox_id = app_conversation_info.sandbox_id
- sandbox_is_shared = False
- if sandbox_id:
- conversation_count = await app_conversation_info_service.count_conversations_by_sandbox_id(
- sandbox_id
- )
- sandbox_is_shared = conversation_count > 1
-
- # This is a V1 conversation, delete it using the app conversation service
- result = await app_conversation_service.delete_app_conversation(
- app_conversation_info.id,
- skip_agent_server_delete=sandbox_is_shared,
- )
-
- # Manually commit so that the conversation will vanish from the list
- await db_session.commit()
-
- # Delete the sandbox in the background (checks remaining conversations first)
- asyncio.create_task(
- _finalize_delete_and_close_connections(
- sandbox_service,
- app_conversation_info.sandbox_id,
- db_session,
- httpx_client,
- )
- )
- except Exception:
- # Continue with V0 logic
- pass
-
- return result
-
-
-async def _finalize_delete_and_close_connections(
- sandbox_service: SandboxService,
- sandbox_id: str,
- db_session: AsyncSession,
- httpx_client: httpx.AsyncClient,
-):
- try:
- num_conversations_in_sandbox = await _get_num_conversations_in_sandbox(
- sandbox_service, sandbox_id, httpx_client
- )
- if num_conversations_in_sandbox == 0:
- await sandbox_service.delete_sandbox(sandbox_id)
- await db_session.commit()
- finally:
- await asyncio.gather(
- *[
- db_session.aclose(),
- httpx_client.aclose(),
- ]
- )
-
-
-async def _get_num_conversations_in_sandbox(
- sandbox_service: SandboxService,
- sandbox_id: str,
- httpx_client: httpx.AsyncClient,
-) -> int:
- try:
- sandbox = await sandbox_service.get_sandbox(sandbox_id)
- if not sandbox or not sandbox.exposed_urls:
- return 0
- agent_server_url = next(
- u for u in sandbox.exposed_urls if u.name == AGENT_SERVER
- )
- headers = (
- {'X-Session-API-Key': sandbox.session_api_key}
- if sandbox.session_api_key
- else {}
- )
- response = await httpx_client.get(
- f'{agent_server_url.url}/api/conversations/count',
- headers=headers,
- )
- result = int(response.content)
- return result
- except Exception:
- return 0
-
-
-async def _delete_v0_conversation(conversation_id: str, user_id: str | None) -> bool:
- """Delete a V0 conversation using the legacy logic."""
- conversation_store = await ConversationStoreImpl.get_instance(config, user_id)
- try:
- await conversation_store.get_metadata(conversation_id)
- except FileNotFoundError:
- return False
-
- # Stop the conversation if it's running
- is_running = await conversation_manager.is_agent_loop_running(conversation_id)
- if is_running:
- await conversation_manager.close_session(conversation_id)
-
- # Clean up runtime and metadata
- runtime_cls = get_runtime_cls(config.runtime)
- await runtime_cls.delete(conversation_id)
- await conversation_store.delete_metadata(conversation_id)
- return True
-
-
[email protected]('/conversations/{conversation_id}/remember-prompt', deprecated=True)
-async def get_prompt(
- event_id: int,
- conversation_id: str = Depends(validate_conversation_id),
- user_settings: SettingsStore = Depends(get_user_settings_store),
- metadata: ConversationMetadata = Depends(get_conversation_metadata),
-):
- """Get the remember prompt for the microagent UI.
-
- .. deprecated::
- This endpoint is deprecated. Microagent UI is deprecated in V1.
- """
- # get event store for the conversation
- event_store = EventStore(
- sid=conversation_id, file_store=file_store, user_id=metadata.user_id
- )
-
- # retrieve the relevant events
- stringified_events = _get_contextual_events(event_store, event_id)
-
- # generate a prompt
- settings = await user_settings.load()
- if settings is None:
- # placeholder for error handling
- raise ValueError('Settings not found')
-
- agent_settings = settings.agent_settings
- settings_base_url = agent_settings.llm.base_url
- effective_base_url = get_effective_llm_base_url(
- agent_settings.llm.model,
- settings_base_url,
- )
- raw_api_key = settings.agent_settings.llm.api_key
- api_key = SecretStr(raw_api_key) if isinstance(raw_api_key, str) else raw_api_key
- llm_config = LLMConfig(
- model=agent_settings.llm.model,
- api_key=api_key,
- base_url=effective_base_url,
- )
-
- prompt_template = generate_prompt_template(stringified_events)
- prompt = await generate_prompt(llm_config, prompt_template, conversation_id)
-
- return JSONResponse(
- {
- 'status': 'success',
- 'prompt': prompt,
- }
- )
-
-
-def generate_prompt_template(events: str) -> str:
- env = Environment(loader=FileSystemLoader('openhands/microagent/prompts'))
- template = env.get_template('generate_remember_prompt.j2')
- return template.render(events=events)
-
-
-async def generate_prompt(
- llm_config: LLMConfig, prompt_template: str, conversation_id: str
-) -> str:
- messages = [
- {
- 'role': 'system',
- 'content': prompt_template,
- },
- {
- 'role': 'user',
- 'content': 'Please generate a prompt for the AI to update the special file based on the events provided.',
- },
- ]
-
- raw_prompt = await conversation_manager.request_llm_completion(
- 'remember_prompt', conversation_id, llm_config, messages
- )
- prompt = re.search(r'<update_prompt>(.*?)</update_prompt>', raw_prompt, re.DOTALL)
-
- if prompt:
- return prompt.group(1).strip()
- else:
- raise ValueError('No valid prompt found in the response.')
-
-
-async def _get_conversation_info(
- conversation: ConversationMetadata,
- num_connections: int,
- agent_loop_info: AgentLoopInfo | None,
-) -> ConversationInfo | None:
- try:
- title = conversation.title
- if not title:
- title = get_default_conversation_title(conversation.conversation_id)
- return ConversationInfo(
- trigger=conversation.trigger,
- conversation_id=conversation.conversation_id,
- title=title,
- last_updated_at=conversation.last_updated_at,
- created_at=conversation.created_at,
- selected_repository=conversation.selected_repository,
- selected_branch=conversation.selected_branch,
- git_provider=conversation.git_provider,
- status=getattr(agent_loop_info, 'status', ConversationStatus.STOPPED),
- runtime_status=getattr(agent_loop_info, 'runtime_status', None),
- num_connections=num_connections,
- url=agent_loop_info.url if agent_loop_info else None,
- session_api_key=getattr(agent_loop_info, 'session_api_key', None),
- pr_number=conversation.pr_number,
- sandbox_id=None, # V0 conversations don't have sandbox_id
- )
- except Exception as e:
- logger.error(
- f'Error loading conversation {conversation.conversation_id}: {str(e)}',
- extra={'session_id': conversation.conversation_id},
- )
- return None
-
-
[email protected]('/conversations/{conversation_id}/start', deprecated=True)
-async def start_conversation(
- providers_set: ProvidersSetModel,
- conversation_id: str = Depends(validate_conversation_id),
- user_id: str = Depends(get_user_id),
- provider_tokens: PROVIDER_TOKEN_TYPE = Depends(get_provider_tokens),
- settings: Settings = Depends(get_user_settings),
- conversation_store: ConversationStore = Depends(get_conversation_store),
-) -> ConversationResponse:
- """Start an agent loop for a conversation.
-
- This endpoint calls the conversation_manager's maybe_start_agent_loop method
- to start a conversation. If the conversation is already running, it will
- return the existing agent loop info.
-
- Use the V1 endpoint ``POST /api/v1/app-conversations`` instead, which combines
- conversation creation and starting into a single operation with integrated
- sandbox lifecycle management.
- """
- logger.info(
- f'Starting conversation: {conversation_id}',
- extra={'session_id': conversation_id},
- )
-
- # Log token fetch status
- if provider_tokens:
- logger.info(
- f'/start endpoint: Fetched provider tokens: {list(provider_tokens.keys())}',
- extra={'session_id': conversation_id},
- )
- else:
- logger.warning(
- '/start endpoint: No provider tokens fetched (provider_tokens is None/empty)',
- extra={'session_id': conversation_id},
- )
-
- try:
- # Check that the conversation exists
- try:
- await conversation_store.get_metadata(conversation_id)
- except Exception:
- return JSONResponse(
- content={
- 'status': 'error',
- 'conversation_id': conversation_id,
- },
- status_code=status.HTTP_404_NOT_FOUND,
- )
-
- # Set up conversation init data with provider information
- conversation_init_data = await setup_init_conversation_settings(
- user_id, conversation_id, providers_set.providers_set or [], provider_tokens
- )
-
- # Start the agent loop
- agent_loop_info = await conversation_manager.maybe_start_agent_loop(
- sid=conversation_id,
- settings=conversation_init_data,
- user_id=user_id,
- )
-
- return ConversationResponse(
- status='ok',
- conversation_id=conversation_id,
- conversation_status=agent_loop_info.status,
- )
- except Exception as e:
- logger.error(
- f'Error starting conversation {conversation_id}: {str(e)}',
- extra={'session_id': conversation_id},
- )
- return JSONResponse(
- content={
- 'status': 'error',
- 'conversation_id': conversation_id,
- 'message': f'Failed to start conversation: {str(e)}',
- },
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
-
[email protected]('/conversations/{conversation_id}/stop', deprecated=True)
-async def stop_conversation(
- conversation_id: str = Depends(validate_conversation_id),
- user_id: str = Depends(get_user_id),
-) -> ConversationResponse:
- """Stop an agent loop for a conversation.
-
- This endpoint calls the conversation_manager's close_session method
- to stop a conversation.
-
- Use the V1 endpoint ``POST /api/v1/sandboxes/{sandbox_id}/pause`` instead to pause
- the sandbox execution, or ``DELETE /api/v1/sandboxes/{sandbox_id}`` to fully stop
- and remove the sandbox.
- """
- logger.info(f'Stopping conversation: {conversation_id}')
-
- try:
- # Check if the conversation is running
- agent_loop_info = await conversation_manager.get_agent_loop_info(
- user_id=user_id, filter_to_sids={conversation_id}
- )
- conversation_status = (
- agent_loop_info[0].status if agent_loop_info else ConversationStatus.STOPPED
- )
-
- if conversation_status not in (
- ConversationStatus.STARTING,
- ConversationStatus.RUNNING,
- ):
- return ConversationResponse(
- status='ok',
- conversation_id=conversation_id,
- message='Conversation was not running',
- conversation_status=conversation_status,
- )
-
- # Stop the conversation
- await conversation_manager.close_session(conversation_id)
-
- return ConversationResponse(
- status='ok',
- conversation_id=conversation_id,
- message='Conversation stopped successfully',
- conversation_status=conversation_status,
- )
- except Exception as e:
- logger.error(
- f'Error stopping conversation {conversation_id}: {str(e)}',
- extra={'session_id': conversation_id},
- )
- return JSONResponse(
- content={
- 'status': 'error',
- 'conversation_id': conversation_id,
- 'message': f'Failed to stop conversation: {str(e)}',
- },
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
-
-def _get_contextual_events(event_store: EventStore, event_id: int) -> str:
- # find the specified events to learn from
- # Get X events around the target event
- context_size = 4
-
- agent_event_filter = EventFilter(
- exclude_hidden=True,
- exclude_types=(
- NullAction,
- NullObservation,
- ChangeAgentStateAction,
- AgentStateChangedObservation,
- ),
- ) # the types of events that can be in an agent's history
-
- # from event_id - context_size to event_id..
- context_before = event_store.search_events(
- start_id=event_id,
- filter=agent_event_filter,
- reverse=True,
- limit=context_size,
- )
-
- # from event_id to event_id + context_size + 1
- context_after = event_store.search_events(
- start_id=event_id + 1,
- filter=agent_event_filter,
- limit=context_size + 1,
- )
-
- # context_before is in reverse chronological order, so convert to list and reverse it.
- ordered_context_before = list(context_before)
- ordered_context_before.reverse()
-
- all_events = itertools.chain(ordered_context_before, context_after)
- stringified_events = '\n'.join(str(event) for event in all_events)
- return stringified_events
-
-
-class UpdateConversationRequest(BaseModel):
- """Request model for updating conversation metadata."""
-
- title: str = Field(
- ..., min_length=1, max_length=200, description='New conversation title'
- )
-
- model_config = ConfigDict(extra='forbid')
-
-
-async def _update_v1_conversation(
- conversation_uuid: uuid.UUID,
- new_title: str,
- user_id: str | None,
- app_conversation_info_service: AppConversationInfoService,
- app_conversation_service: AppConversationService,
-) -> JSONResponse | bool:
- """Update a V1 conversation title.
-
- Args:
- conversation_uuid: The conversation ID as a UUID
- new_title: The new title to set
- user_id: The authenticated user ID
- app_conversation_info_service: The app conversation info service
- app_conversation_service: The app conversation service for agent-server communication
-
- Returns:
- JSONResponse on error, True on success
- """
- conversation_id = str(conversation_uuid)
- logger.info(
- f'Updating V1 conversation {conversation_uuid}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
-
- # Get the V1 conversation info
- app_conversation_info = (
- await app_conversation_info_service.get_app_conversation_info(conversation_uuid)
- )
-
- if not app_conversation_info:
- # Not a V1 conversation
- return None
-
- # Validate that the user owns this conversation
- if user_id and app_conversation_info.created_by_user_id != user_id:
- logger.warning(
- f'User {user_id} attempted to update V1 conversation {conversation_uuid} owned by {app_conversation_info.created_by_user_id}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
- return JSONResponse(
- content={
- 'status': 'error',
- 'message': 'Permission denied: You can only update your own conversations',
- 'msg_id': 'AUTHORIZATION$PERMISSION_DENIED',
- },
- status_code=status.HTTP_403_FORBIDDEN,
- )
-
- # Update the title and timestamp
- original_title = app_conversation_info.title
- app_conversation_info.title = new_title
- app_conversation_info.updated_at = datetime.now(timezone.utc)
-
- # Save the updated conversation info
- try:
- await app_conversation_info_service.save_app_conversation_info(
- app_conversation_info
- )
- except AssertionError:
- # This happens when user doesn't own the conversation
- logger.warning(
- f'User {user_id} attempted to update V1 conversation {conversation_uuid} - permission denied',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
- return JSONResponse(
- content={
- 'status': 'error',
- 'message': 'Permission denied: You can only update your own conversations',
- 'msg_id': 'AUTHORIZATION$PERMISSION_DENIED',
- },
- status_code=status.HTTP_403_FORBIDDEN,
- )
-
- # Try to update the agent-server as well
- try:
- if hasattr(app_conversation_service, 'update_agent_server_conversation_title'):
- await app_conversation_service.update_agent_server_conversation_title(
- conversation_id=conversation_id,
- new_title=new_title,
- app_conversation_info=app_conversation_info,
- )
- except Exception as e:
- # Log the error but don't fail the database update
- logger.warning(
- f'Failed to update agent-server for conversation {conversation_uuid}: {e}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
-
- logger.info(
- f'Successfully updated V1 conversation {conversation_uuid} title from "{original_title}" to "{app_conversation_info.title}"',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
-
- return True
-
-
-async def _update_v0_conversation(
- conversation_id: str,
- new_title: str,
- user_id: str | None,
- conversation_store: ConversationStore,
-) -> JSONResponse | bool:
- """Update a V0 conversation title.
-
- Args:
- conversation_id: The conversation ID
- new_title: The new title to set
- user_id: The authenticated user ID
- conversation_store: The conversation store
-
- Returns:
- JSONResponse on error, True on success
-
- Raises:
- FileNotFoundError: If the conversation is not found
- """
- logger.info(
- f'Updating V0 conversation {conversation_id}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
-
- # Get the existing conversation metadata
- metadata = await conversation_store.get_metadata(conversation_id)
-
- # Validate that the user owns this conversation
- if user_id and metadata.user_id != user_id:
- logger.warning(
- f'User {user_id} attempted to update conversation {conversation_id} owned by {metadata.user_id}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
- return JSONResponse(
- content={
- 'status': 'error',
- 'message': 'Permission denied: You can only update your own conversations',
- 'msg_id': 'AUTHORIZATION$PERMISSION_DENIED',
- },
- status_code=status.HTTP_403_FORBIDDEN,
- )
-
- # Update the conversation metadata
- original_title = metadata.title
- metadata.title = new_title
- metadata.last_updated_at = datetime.now(timezone.utc)
-
- # Save the updated metadata
- await conversation_store.save_metadata(metadata)
-
- # Emit a status update to connected clients about the title change
- try:
- status_update_dict = {
- 'status_update': True,
- 'type': 'info',
- 'message': conversation_id,
- 'conversation_title': metadata.title,
- }
- await conversation_manager.sio.emit(
- 'oh_event',
- status_update_dict,
- to=f'room:{conversation_id}',
- )
- except Exception as e:
- logger.error(f'Error emitting title update event: {e}')
- # Don't fail the update if we can't emit the event
-
- logger.info(
- f'Successfully updated conversation {conversation_id} title from "{original_title}" to "{metadata.title}"',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
-
- return True
-
-
[email protected]('/conversations/{conversation_id}', deprecated=True)
-async def update_conversation(
- data: UpdateConversationRequest,
- conversation_id: str = Depends(validate_conversation_id),
- user_id: str | None = Depends(get_user_id),
- conversation_store: ConversationStore = Depends(get_conversation_store),
- app_conversation_info_service: AppConversationInfoService = app_conversation_info_service_dependency,
- app_conversation_service: AppConversationService = app_conversation_service_dependency,
-) -> bool:
- """Update conversation metadata.
-
- This endpoint allows updating conversation details like title.
- Only the conversation owner can update the conversation.
- Supports both V0 and V1 conversations.
-
- Args:
- conversation_id: The ID of the conversation to update
- data: The conversation update data (title, etc.)
- user_id: The authenticated user ID
- conversation_store: The conversation store dependency
- app_conversation_info_service: The app conversation info service for V1 conversations
- app_conversation_service: The app conversation service for agent-server communication
-
- Returns:
- bool: True if the conversation was updated successfully
-
- Raises:
- HTTPException: If conversation is not found or user lacks permission
-
- This endpoint is part of the legacy V0 API and will be removed in a future release.
- Use the V1 endpoint ``PATCH /api/v1/app-conversations/{conversation_id}`` instead,
- which provides the same functionality for updating conversation metadata.
- """
- logger.info(
- f'Updating conversation {conversation_id} with title: {data.title}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
-
- new_title = data.title.strip()
-
- # Try to handle as V1 conversation first
- try:
- conversation_uuid = uuid.UUID(conversation_id)
- result = await _update_v1_conversation(
- conversation_uuid=conversation_uuid,
- new_title=new_title,
- user_id=user_id,
- app_conversation_info_service=app_conversation_info_service,
- app_conversation_service=app_conversation_service,
- )
-
- # If result is not None, it's a V1 conversation (either success or error)
- if result is not None:
- return result
-
- except (ValueError, TypeError):
- # Not a valid UUID, fall through to V0 logic
- pass
- except Exception as e:
- logger.warning(
- f'Error checking V1 conversation {conversation_id}: {str(e)}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
- # Fall through to V0 logic
-
- # Handle as V0 conversation
- try:
- return await _update_v0_conversation(
- conversation_id=conversation_id,
- new_title=new_title,
- user_id=user_id,
- conversation_store=conversation_store,
- )
- except FileNotFoundError:
- logger.warning(
- f'Conversation {conversation_id} not found for update',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
- return JSONResponse(
- content={
- 'status': 'error',
- 'message': 'Conversation not found',
- 'msg_id': 'CONVERSATION$NOT_FOUND',
- },
- status_code=status.HTTP_404_NOT_FOUND,
- )
- except Exception as e:
- logger.error(
- f'Error updating conversation {conversation_id}: {str(e)}',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
- return JSONResponse(
- content={
- 'status': 'error',
- 'message': f'Failed to update conversation: {str(e)}',
- 'msg_id': 'CONVERSATION$UPDATE_ERROR',
- },
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
-
-def _parse_combined_page_id(page_id: str | None) -> tuple[str | None, str | None]:
- """Parse combined page_id to extract separate V0 and V1 page_ids.
-
- Args:
- page_id: Combined page_id (base64-encoded JSON) or legacy V0 page_id
-
- Returns:
- Tuple of (v0_page_id, v1_page_id)
- """
- v0_page_id = None
- v1_page_id = None
-
- if page_id:
- try:
- # Try to parse as JSON first
- page_data = json.loads(base64.b64decode(page_id))
- v0_page_id = page_data.get('v0')
- v1_page_id = page_data.get('v1')
- except (json.JSONDecodeError, TypeError, Exception):
- # Fallback: treat as v0 page_id for backward compatibility
- # This catches base64 decode errors and any other parsing issues
- v0_page_id = page_id
-
- return v0_page_id, v1_page_id
-
-
-async def _fetch_v1_conversations_safe(
- app_conversation_service: AppConversationService,
- v1_page_id: str | None,
- limit: int,
-) -> tuple[list[ConversationInfo], str | None]:
- """Safely fetch V1 conversations with error handling.
-
- Args:
- app_conversation_service: App conversation service for V1
- v1_page_id: Page ID for V1 pagination
- limit: Maximum number of results
- include_sub_conversations: If True, include sub-conversations in results
-
- Returns:
- Tuple of (v1_conversations, v1_next_page_id)
- """
- v1_conversations = []
- v1_next_page_id = None
-
- try:
- age_filter_date = None
- if config.conversation_max_age_seconds:
- age_filter_date = datetime.now(timezone.utc) - timedelta(
- seconds=config.conversation_max_age_seconds
- )
-
- app_conversation_page = await app_conversation_service.search_app_conversations(
- page_id=v1_page_id,
- limit=limit,
- created_at__gte=age_filter_date,
- )
-
- v1_conversations = [
- _to_conversation_info(app_conv) for app_conv in app_conversation_page.items
- ]
- v1_next_page_id = app_conversation_page.next_page_id
- except Exception as e:
- # V1 system might not be available or initialized yet
- logger.debug(f'V1 conversation service not available: {str(e)}')
-
- return v1_conversations, v1_next_page_id
-
-
-async def _process_v0_conversations(
- conversation_metadata_result_set,
-) -> list[ConversationInfo]:
- """Process V0 conversations with age filtering and agent loop info.
-
- Args:
- conversation_metadata_result_set: Result set from V0 conversation store
-
- Returns:
- List of processed ConversationInfo objects
- """
- # Apply age filter to V0 conversations
- v0_filtered_results = _filter_conversations_by_age(
- conversation_metadata_result_set.results,
- config.conversation_max_age_seconds,
- )
-
- v0_conversation_ids = set(
- conversation.conversation_id for conversation in v0_filtered_results
- )
-
- # Get agent loop info for V0 conversations
- await conversation_manager.get_connections(filter_to_sids=v0_conversation_ids)
- v0_agent_loop_info = await conversation_manager.get_agent_loop_info(
- filter_to_sids=v0_conversation_ids
- )
- v0_agent_loop_info_by_conversation_id = {
- info.conversation_id: info for info in v0_agent_loop_info
- }
-
- # Convert to ConversationInfo objects
- v0_conversations = await wait_all(
- _get_conversation_info(
- conversation=conversation,
- num_connections=sum(
- 1
- for conversation_id in v0_agent_loop_info_by_conversation_id.values()
- if conversation_id == conversation.conversation_id
- ),
- agent_loop_info=v0_agent_loop_info_by_conversation_id.get(
- conversation.conversation_id
- ),
- )
- for conversation in v0_filtered_results
- )
-
- return v0_conversations
-
-
-async def _apply_microagent_filters(
- conversations: list[ConversationInfo],
- selected_repository: str,
- provider_handler: ProviderHandler,
-) -> list[ConversationInfo]:
- """Apply microagent management specific filters to conversations.
-
- Filters conversations by:
- - Trigger type (MICROAGENT_MANAGEMENT)
- - Repository match
- - PR status (only open PRs)
-
- Args:
- conversations: List of conversations to filter
- selected_repository: Repository to filter by
- provider_handler: Handler for checking PR status
-
- Returns:
- Filtered list of conversations
- """
- filtered = []
- for conversation in conversations:
- # Only include microagent_management conversations
- if conversation.trigger != ConversationTrigger.MICROAGENT_MANAGEMENT:
- continue
-
- # Apply repository filter
- if conversation.selected_repository != selected_repository:
- continue
-
- # Check if PR is still open
- if (
- conversation.pr_number
- and len(conversation.pr_number) > 0
- and conversation.selected_repository
- and conversation.git_provider
- and not await provider_handler.is_pr_open(
- conversation.selected_repository,
- conversation.pr_number[-1], # Get the last PR number
- conversation.git_provider,
- )
- ):
- # Skip this conversation if the PR is closed/merged
- continue
-
- filtered.append(conversation)
-
- return filtered
-
-
-def _create_combined_page_id(
- v0_next_page_id: str | None, v1_next_page_id: str | None
-) -> str | None:
- """Create a combined page_id from V0 and V1 page_ids.
-
- Args:
- v0_next_page_id: Next page ID for V0 conversations
- v1_next_page_id: Next page ID for V1 conversations
-
- Returns:
- Base64-encoded JSON combining both page_ids, or None if no next pages
- """
- if not v0_next_page_id and not v1_next_page_id:
- return None
-
- next_page_data = {
- 'v0': v0_next_page_id,
- 'v1': v1_next_page_id,
- }
-
- return base64.b64encode(json.dumps(next_page_data).encode()).decode()
-
-
[email protected]('/microagent-management/conversations', deprecated=True)
-async def get_microagent_management_conversations(
- selected_repository: str,
- page_id: str | None = None,
- limit: int = 20,
- conversation_store: ConversationStore = Depends(get_conversation_store),
- provider_tokens: PROVIDER_TOKEN_TYPE = Depends(get_provider_tokens),
- app_conversation_service: AppConversationService = app_conversation_service_dependency,
-) -> ConversationInfoResultSet:
- """Get conversations for the microagent management page with pagination support.
-
- .. deprecated::
- This endpoint is deprecated. Microagent UI is deprecated in V1.
-
- This endpoint returns conversations with conversation_trigger = 'microagent_management'
- and only includes conversations with active PRs. Pagination is supported.
-
- Args:
- page_id: Optional page ID for pagination
- limit: Maximum number of results per page (default: 20)
- selected_repository: Repository filter to limit results to a specific repository
- conversation_store: Conversation store dependency
- provider_tokens: Provider tokens for checking PR status
- app_conversation_service: App conversation service for V1 conversations
-
- Returns:
- ConversationInfoResultSet with filtered and paginated results
- """
- # Parse page_id to extract V0 and V1 components
- v0_page_id, v1_page_id = _parse_combined_page_id(page_id)
-
- # Fetch V0 conversations
- conversation_metadata_result_set = await conversation_store.search(
- v0_page_id, limit
- )
-
- # Fetch V1 conversations (with graceful error handling)
- v1_conversations, v1_next_page_id = await _fetch_v1_conversations_safe(
- app_conversation_service, v1_page_id, limit
- )
-
- # Process V0 conversations
- v0_conversations = await _process_v0_conversations(conversation_metadata_result_set)
-
- # Apply microagent-specific filters
- provider_handler = ProviderHandler(provider_tokens)
- v0_filtered = await _apply_microagent_filters(
- v0_conversations, selected_repository, provider_handler
- )
- v1_filtered = await _apply_microagent_filters(
- v1_conversations, selected_repository, provider_handler
- )
-
- # Combine and sort results
- all_conversations = v0_filtered + v1_filtered
- all_conversations.sort(
- key=lambda x: x.created_at or datetime.min.replace(tzinfo=timezone.utc),
- reverse=True,
- )
-
- # Limit to requested number of results
- final_results = all_conversations[:limit]
-
- # Create combined page_id for pagination
- next_page_id = _create_combined_page_id(
- conversation_metadata_result_set.next_page_id, v1_next_page_id
- )
-
- return ConversationInfoResultSet(results=final_results, next_page_id=next_page_id)
-
-
-def _to_conversation_info(app_conversation: AppConversation) -> ConversationInfo:
- """Convert a V1 AppConversation into an old style ConversationInfo"""
- from openhands.app_server.sandbox.sandbox_models import SandboxStatus
-
- # Map SandboxStatus to ConversationStatus
- conversation_status_mapping = {
- SandboxStatus.RUNNING: ConversationStatus.RUNNING,
- SandboxStatus.STARTING: ConversationStatus.STARTING,
- SandboxStatus.PAUSED: ConversationStatus.STOPPED,
- SandboxStatus.ERROR: ConversationStatus.ERROR,
- SandboxStatus.MISSING: ConversationStatus.ARCHIVED,
- }
-
- conversation_status = conversation_status_mapping.get(
- app_conversation.sandbox_status, ConversationStatus.STOPPED
- )
-
- if conversation_status == ConversationStatus.RUNNING:
- runtime_status_mapping = {
- ConversationExecutionStatus.ERROR: RuntimeStatus.ERROR,
- ConversationExecutionStatus.IDLE: RuntimeStatus.READY,
- ConversationExecutionStatus.RUNNING: RuntimeStatus.READY,
- ConversationExecutionStatus.PAUSED: RuntimeStatus.READY,
- ConversationExecutionStatus.WAITING_FOR_CONFIRMATION: RuntimeStatus.READY,
- ConversationExecutionStatus.FINISHED: RuntimeStatus.READY,
- ConversationExecutionStatus.STUCK: RuntimeStatus.ERROR,
- }
- if app_conversation.execution_status:
- runtime_status = runtime_status_mapping.get(
- app_conversation.execution_status, RuntimeStatus.ERROR
- )
- else:
- runtime_status = RuntimeStatus.ERROR
- else:
- runtime_status = None
-
- title = (
- app_conversation.title
- or f'Conversation {base62.encodebytes(app_conversation.id.bytes)}'
- )
-
- return ConversationInfo(
- conversation_id=app_conversation.id.hex,
- title=title,
- last_updated_at=app_conversation.updated_at,
- status=conversation_status,
- runtime_status=runtime_status,
- selected_repository=app_conversation.selected_repository,
- selected_branch=app_conversation.selected_branch,
- git_provider=app_conversation.git_provider,
- trigger=app_conversation.trigger,
- num_connections=0, # V1 conversations don't track connections the same way
- url=app_conversation.conversation_url,
- session_api_key=app_conversation.session_api_key,
- created_at=app_conversation.created_at,
- pr_number=app_conversation.pr_number,
- conversation_version='V1',
- sub_conversation_ids=[
- sub_id.hex for sub_id in app_conversation.sub_conversation_ids
- ],
- public=app_conversation.public,
- sandbox_id=app_conversation.sandbox_id,
- llm_model=app_conversation.llm_model,
- )
diff --git a/openhands/server/routes/public.py b/openhands/server/routes/public.py
index 3ceb3f0bbd..a840210bc8 100644
--- a/openhands/server/routes/public.py
+++ b/openhands/server/routes/public.py
@@ -1,24 +1,10 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
+# Function migrated from the deprecated routes/public.py
+# This is used by the V1 config router to get LLM models
+from fastapi import Request
-from typing import Any
-
-from fastapi import APIRouter, Depends, Request
-
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.controller.agent import Agent
-from openhands.security.options import SecurityAnalyzers
-from openhands.server.shared import config, server_config
+from openhands.server.shared import config
from openhands.utils.llm import ModelsResponse, get_supported_llm_models
-app = APIRouter(prefix='/api/options', dependencies=get_dependencies())
-
async def get_llm_models_dependency(request: Request) -> ModelsResponse:
"""Returns a callable that provides the LLM models implementation.
@@ -27,69 +13,3 @@ async def get_llm_models_dependency(request: Request) -> ModelsResponse:
Override this in enterprise/saas mode via app.dependency_overrides.
"""
return get_supported_llm_models(config)
-
-
[email protected]('/models', deprecated=True)
-async def get_litellm_models(
- models: ModelsResponse = Depends(get_llm_models_dependency),
-) -> ModelsResponse:
- """Get all supported LLM models.
-
- .. deprecated::
- This endpoint is deprecated. Use `/api/v1/config/models/search` instead.
-
- Returns:
- ModelsResponse: Response containing models, verified_models, verified_providers, and default_model.
- """
- return models
-
-
[email protected]('/agents', response_model=list[str], deprecated=True)
-async def get_agents() -> list[str]:
- """Get all agents supported by LiteLLM.
-
- .. deprecated::
- This endpoint is deprecated. The agent definitions are now part of the
- OpenAPI schema so this is no longer required.
-
- To get the agents:
- ```sh
- curl http://localhost:3000/api/agents
- ```
-
- Returns:
- list[str]: A sorted list of agent names.
- """
- return sorted(Agent.list_agents())
-
-
[email protected]('/security-analyzers', response_model=list[str], deprecated=True)
-async def get_security_analyzers() -> list[str]:
- """Get all supported security analyzers.
-
- .. deprecated::
- This endpoint is deprecated. The security analyzers are now part of the
- OpenAPI schema so this is no longer required.
-
- To get the security analyzers:
- ```sh
- curl http://localhost:3000/api/security-analyzers
- ```
-
- Returns:
- list[str]: A sorted list of security analyzer names.
- """
- return sorted(SecurityAnalyzers.keys())
-
-
[email protected]('/config', response_model=dict[str, Any], deprecated=True)
-async def get_config() -> dict[str, Any]:
- """Get current config.
-
- This method has been replaced with the /v1/web-client/config endpoint,
- and will be removed as part of the V0 cleanup on 2026-04-01
-
- Returns:
- dict[str, Any]: The current server configuration.
- """
- return server_config.get_config()
diff --git a/openhands/server/routes/secrets.py b/openhands/server/routes/secrets.py
deleted file mode 100644
index 3d55ae51c7..0000000000
--- a/openhands/server/routes/secrets.py
+++ /dev/null
@@ -1,173 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from fastapi import APIRouter, Depends, status
-
-from openhands.app_server.secrets.secrets_router import (
- create_custom_secret as v1_create_custom_secret,
-)
-from openhands.app_server.secrets.secrets_router import (
- delete_custom_secret as v1_delete_custom_secret,
-)
-from openhands.app_server.secrets.secrets_router import search_custom_secrets
-from openhands.app_server.secrets.secrets_router import (
- store_provider_tokens as v1_store_provider_tokens,
-)
-from openhands.app_server.secrets.secrets_router import (
- unset_provider_tokens as v1_unset_provider_tokens,
-)
-from openhands.app_server.secrets.secrets_router import (
- update_custom_secret as v1_update_custom_secret,
-)
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.app_server.utils.models import EditResponse
-from openhands.integrations.provider import PROVIDER_TOKEN_TYPE
-from openhands.sdk.utils.paging import page_iterator
-from openhands.server.settings import (
- CustomSecretModel,
- CustomSecretWithoutValueModel,
- GETCustomSecrets,
- POSTProviderModel,
-)
-from openhands.server.user_auth import (
- get_provider_tokens,
- get_secrets,
- get_secrets_store,
-)
-from openhands.storage.data_models.secrets import Secrets
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.secrets.secrets_store import SecretsStore
-from openhands.storage.settings.settings_store import SettingsStore
-
-app = APIRouter(prefix='/api', dependencies=get_dependencies())
-
-
-# =================================================
-# SECTION: Handle git provider tokens
-# =================================================
-
-
-async def invalidate_legacy_secrets_store(
- settings: Settings, settings_store: SettingsStore, secrets_store: SecretsStore
-) -> Secrets | None:
- """We are moving `secrets_store` (a field from `Settings` object) to its own dedicated store
- This function moves the values from Settings to Secrets, and deletes the values in Settings
- While this function in called multiple times, the migration only ever happens once
- """
- if len(settings.secrets_store.provider_tokens.items()) > 0:
- user_secrets = Secrets(provider_tokens=settings.secrets_store.provider_tokens)
- await secrets_store.store(user_secrets)
-
- # Invalidate old tokens via settings store serializer
- invalidated_secrets_settings = settings.model_copy(
- update={'secrets_store': Secrets()}
- )
- await settings_store.store(invalidated_secrets_settings)
-
- return user_secrets
-
- return None
-
-
[email protected]('/add-git-providers', deprecated=True)
-async def store_provider_tokens(
- provider_info: POSTProviderModel,
- secrets_store: SecretsStore = Depends(get_secrets_store),
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
-) -> EditResponse:
- """Store git provider tokens.
-
- .. deprecated::
- Use ``POST /api/v1/secrets/git-providers`` instead. This V0 endpoint will be removed
- April 1, 2026.
- """
- return await v1_store_provider_tokens(provider_info, secrets_store, provider_tokens)
-
-
[email protected]('/unset-provider-tokens', deprecated=True)
-async def unset_provider_tokens(
- secrets_store: SecretsStore = Depends(get_secrets_store),
-) -> EditResponse:
- """Unset (delete) all git provider tokens.
-
- .. deprecated::
- Use ``DELETE /api/v1/secrets/git-providers`` instead. This V0 endpoint will be removed
- April 1, 2026.
- """
- return await v1_unset_provider_tokens(secrets_store)
-
-
-# =================================================
-# SECTION: Handle custom secrets
-# =================================================
-
-
[email protected]('/secrets', response_model=GETCustomSecrets, deprecated=True)
-async def load_custom_secrets_names(
- user_secrets: Secrets | None = Depends(get_secrets),
-) -> GETCustomSecrets:
- """Load custom secret names.
-
- .. deprecated::
- Use ``GET /api/v1/secrets/search`` instead. This V0 endpoint will be removed
- April 1, 2026. The V1 endpoint provides pagination and filtering support.
- """
- custom_secrets = []
- async for custom_secret in page_iterator(
- search_custom_secrets, user_secrets=user_secrets
- ):
- custom_secrets.append(
- CustomSecretWithoutValueModel(
- name=custom_secret.name, description=custom_secret.description
- )
- )
- result = GETCustomSecrets(custom_secrets=custom_secrets)
- return result
-
-
[email protected]('/secrets', status_code=status.HTTP_201_CREATED, deprecated=True)
-async def create_custom_secret(
- incoming_secret: CustomSecretModel,
- secrets_store: SecretsStore = Depends(get_secrets_store),
-) -> EditResponse:
- """Create a custom secret.
-
- .. deprecated::
- Use ``POST /api/v1/secrets`` instead. This V0 endpoint will be removed
- April 1, 2026.
- """
- return await v1_create_custom_secret(incoming_secret, secrets_store)
-
-
[email protected]('/secrets/{secret_id}', deprecated=True)
-async def update_custom_secret(
- secret_id: str,
- incoming_secret: CustomSecretWithoutValueModel,
- secrets_store: SecretsStore = Depends(get_secrets_store),
-) -> EditResponse:
- """Update a custom secret.
-
- .. deprecated::
- Use ``PUT /api/v1/secrets/{secret_id}`` instead. This V0 endpoint will be removed
- April 1, 2026.
- """
- return await v1_update_custom_secret(secret_id, incoming_secret, secrets_store)
-
-
[email protected]('/secrets/{secret_id}', deprecated=True)
-async def delete_custom_secret(
- secret_id: str,
- secrets_store: SecretsStore = Depends(get_secrets_store),
-) -> EditResponse:
- """Delete a custom secret.
-
- .. deprecated::
- Use ``DELETE /api/v1/secrets/{secret_id}`` instead. This V0 endpoint will be removed
- April 1, 2026.
- """
- return await v1_delete_custom_secret(secret_id, secrets_store)
diff --git a/openhands/server/routes/settings.py b/openhands/server/routes/settings.py
deleted file mode 100644
index bcbb90f542..0000000000
--- a/openhands/server/routes/settings.py
+++ /dev/null
@@ -1,161 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from typing import Any
-
-from fastapi import APIRouter, Depends, status
-from fastapi.responses import JSONResponse
-
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.core.logger import openhands_logger as logger
-from openhands.integrations.provider import (
- PROVIDER_TOKEN_TYPE,
-)
-from openhands.server.routes.secrets import invalidate_legacy_secrets_store
-from openhands.server.settings import (
- GETSettingsModel,
-)
-from openhands.server.shared import config
-from openhands.server.user_auth import (
- get_provider_tokens,
- get_secrets_store,
- get_user_settings,
- get_user_settings_store,
-)
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.secrets.secrets_store import SecretsStore
-from openhands.storage.settings.settings_store import SettingsStore
-
-app = APIRouter(prefix='/api', dependencies=get_dependencies())
-
-
- '/settings',
- response_model=GETSettingsModel,
- responses={
- 404: {'description': 'Settings not found', 'model': dict},
- 401: {'description': 'Invalid token', 'model': dict},
- },
- deprecated=True,
-)
-async def load_settings(
- provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
- settings_store: SettingsStore = Depends(get_user_settings_store),
- settings: Settings = Depends(get_user_settings),
- secrets_store: SecretsStore = Depends(get_secrets_store),
-) -> GETSettingsModel | JSONResponse:
- try:
- if not settings:
- return JSONResponse(
- status_code=status.HTTP_404_NOT_FOUND,
- content={'error': 'Settings not found'},
- )
-
- user_secrets = await invalidate_legacy_secrets_store(
- settings, settings_store, secrets_store
- )
-
- git_providers = (
- user_secrets.provider_tokens if user_secrets else provider_tokens
- )
-
- provider_tokens_set: dict[str, str | None] = {}
- if git_providers:
- for provider_type, provider_token in git_providers.items():
- if provider_token.token or provider_token.user_id:
- provider_tokens_set[provider_type.value] = provider_token.host
-
- agent_vals = settings.get_agent_settings_display()
- settings_payload = settings.model_dump(
- mode='json', exclude={'agent_settings', 'conversation_settings'}
- )
- settings_payload.update(
- {
- 'llm_api_key_set': settings.llm_api_key_is_set,
- 'search_api_key_set': settings.search_api_key is not None
- and bool(settings.search_api_key),
- 'provider_tokens_set': provider_tokens_set,
- 'agent_settings': agent_vals,
- 'conversation_settings': settings.conversation_settings.model_dump(
- mode='json'
- ),
- 'llm_api_key': None,
- 'search_api_key': None,
- 'sandbox_api_key': None,
- }
- )
- return JSONResponse(status_code=status.HTTP_200_OK, content=settings_payload)
- except Exception as e:
- logger.warning(f'Invalid token: {e}')
- user_id = getattr(settings, 'user_id', 'unknown') if settings else 'unknown'
- logger.info(
- f'Returning 401 Unauthorized - Invalid token for user_id: {user_id}'
- )
- return JSONResponse(
- status_code=status.HTTP_401_UNAUTHORIZED,
- content={'error': 'Invalid token'},
- )
-
-
- '/settings',
- response_model=None,
- responses={
- 200: {'description': 'Settings stored successfully', 'model': dict},
- 500: {'description': 'Error storing settings', 'model': dict},
- },
- deprecated=True,
-)
-async def store_settings(
- payload: dict[str, Any],
- settings_store: SettingsStore = Depends(get_user_settings_store),
-) -> JSONResponse:
- try:
- existing_settings = await settings_store.load()
- settings = existing_settings.model_copy() if existing_settings else Settings()
- settings.update(payload)
-
- if existing_settings:
- if 'search_api_key' not in payload and settings.search_api_key is None:
- settings.search_api_key = existing_settings.search_api_key
- if settings.user_consents_to_analytics is None:
- settings.user_consents_to_analytics = (
- existing_settings.user_consents_to_analytics
- )
- if settings.disabled_skills is None:
- settings.disabled_skills = existing_settings.disabled_skills
-
- if settings.remote_runtime_resource_factor is not None:
- config.sandbox.remote_runtime_resource_factor = (
- settings.remote_runtime_resource_factor
- )
-
- git_config_updated = False
- if settings.git_user_name is not None:
- config.git_user_name = settings.git_user_name
- git_config_updated = True
- if settings.git_user_email is not None:
- config.git_user_email = settings.git_user_email
- git_config_updated = True
-
- if git_config_updated:
- logger.info(
- f'Updated global git configuration: name={config.git_user_name}, email={config.git_user_email}'
- )
-
- await settings_store.store(settings)
- return JSONResponse(
- status_code=status.HTTP_200_OK,
- content={'message': 'Settings stored'},
- )
- except Exception as e:
- logger.warning(f'Something went wrong storing settings: {e}')
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': 'Something went wrong storing settings'},
- )
diff --git a/openhands/server/routes/trajectory.py b/openhands/server/routes/trajectory.py
deleted file mode 100644
index 5a87ea118a..0000000000
--- a/openhands/server/routes/trajectory.py
+++ /dev/null
@@ -1,71 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from fastapi import APIRouter, Depends, status
-from fastapi.responses import JSONResponse
-
-from openhands.app_server.utils.dependencies import get_dependencies
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.async_event_store_wrapper import AsyncEventStoreWrapper
-from openhands.events.event_filter import EventFilter
-from openhands.events.event_store import EventStore
-from openhands.events.serialization import event_to_trajectory
-from openhands.server.shared import file_store
-from openhands.server.utils import get_conversation_metadata
-from openhands.storage.data_models.conversation_metadata import ConversationMetadata
-
-app = APIRouter(
- prefix='/api/conversations/{conversation_id}', dependencies=get_dependencies()
-)
-
-
[email protected]('/trajectory', deprecated=True)
-async def get_trajectory(
- metadata: ConversationMetadata = Depends(get_conversation_metadata),
-) -> JSONResponse:
- """Get trajectory.
-
- .. deprecated::
- This endpoint is deprecated. Use the V1 endpoint
- ``GET /app-conversation/{conversation_id}/download`` instead.
-
- This function retrieves the current trajectory and returns it.
- Uses the local EventStore which reads events from the file store,
- so it works with both standalone and nested conversation managers.
-
- Args:
- metadata: The conversation metadata (provides conversation_id and user access validation).
-
- Returns:
- JSONResponse: A JSON response containing the trajectory as a list of
- events.
- """
- try:
- event_store = EventStore(
- sid=metadata.conversation_id,
- file_store=file_store,
- user_id=metadata.user_id,
- )
- async_store = AsyncEventStoreWrapper(
- event_store, filter=EventFilter(exclude_hidden=True)
- )
- trajectory = []
- async for event in async_store:
- trajectory.append(event_to_trajectory(event))
- return JSONResponse(
- status_code=status.HTTP_200_OK, content={'trajectory': trajectory}
- )
- except Exception as e:
- logger.error(f'Error getting trajectory: {e}', exc_info=True)
- return JSONResponse(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={
- 'trajectory': None,
- 'error': f'Error getting trajectory: {e}',
- },
- )
diff --git a/tests/unit/app_server/test_settings_api.py b/tests/unit/app_server/test_settings_api.py
index 61091fa1fc..6549f77aeb 100644
--- a/tests/unit/app_server/test_settings_api.py
+++ b/tests/unit/app_server/test_settings_api.py
@@ -161,14 +161,14 @@ async def test_settings_api_endpoints(test_client):
),
)
- # Make the POST request to store settings
- response = test_client.post('/api/settings', json=_dump(settings))
+ # Make the POST request to store settings (V1 endpoint)
+ response = test_client.post('/api/v1/settings', json=_dump(settings))
# We're not checking the exact response, just that it doesn't error
assert response.status_code == 200
- # Test the GET settings endpoint
- response = test_client.get('/api/settings')
+ # Test the GET settings endpoint (V1 endpoint)
+ response = test_client.get('/api/v1/settings')
assert response.status_code == 200
response_data = response.json()
assert 'agent_settings_schema' not in response_data
@@ -185,7 +185,9 @@ async def test_settings_api_endpoints(test_client):
assert cs['confirmation_mode'] is True
assert cs['security_analyzer'] == 'llm'
assert cs['max_iterations'] == 100
- assert vals['llm']['api_key'] == '**********'
+ # V1 API sets api_key to None for security and uses llm_api_key_set flag instead
+ assert vals['llm']['api_key'] is None
+ assert response_data['llm_api_key_set'] is True
# Test updating with partial settings β€” legacy flat fields should preserve existing
partial_settings = {
@@ -194,17 +196,13 @@ async def test_settings_api_endpoints(test_client):
'llm_api_key': None,
}
- response = test_client.post('/api/settings', json=partial_settings)
+ response = test_client.post('/api/v1/settings', json=partial_settings)
assert response.status_code == 200
- response = test_client.get('/api/settings')
+ response = test_client.get('/api/v1/settings')
assert response.status_code == 200
assert response.json()['agent_settings']['llm']['timeout'] == 123
- # Test the unset-provider-tokens endpoint
- response = test_client.post('/api/unset-provider-tokens')
- assert response.status_code == 200
-
@pytest.mark.asyncio
async def test_saving_settings_with_frozen_secrets_store(test_client):
@@ -220,7 +218,7 @@ async def test_saving_settings_with_frozen_secrets_store(test_client):
)
# Inject an extra key the API should ignore gracefully
payload['secrets_store'] = {'provider_tokens': {}}
- response = test_client.post('/api/settings', json=payload)
+ response = test_client.post('/api/v1/settings', json=payload)
assert response.status_code == 200
@@ -228,7 +226,7 @@ async def test_saving_settings_with_frozen_secrets_store(test_client):
async def test_search_api_key_explicit_clear(test_client):
"""Explicit empty search_api_key payloads should clear the stored secret."""
response = test_client.post(
- '/api/settings',
+ '/api/v1/settings',
json=_dump(
Settings(
search_api_key='initial-secret-key',
@@ -238,12 +236,12 @@ async def test_search_api_key_explicit_clear(test_client):
)
assert response.status_code == 200
- response = test_client.get('/api/settings')
+ response = test_client.get('/api/v1/settings')
assert response.status_code == 200
assert response.json()['search_api_key_set'] is True
response = test_client.post(
- '/api/settings',
+ '/api/v1/settings',
json=_dump(
Settings(
search_api_key='',
@@ -253,7 +251,7 @@ async def test_search_api_key_explicit_clear(test_client):
)
assert response.status_code == 200
- response = test_client.get('/api/settings')
+ response = test_client.get('/api/v1/settings')
assert response.status_code == 200
assert response.json()['search_api_key_set'] is False
assert response.json()['agent_settings']['llm']['model'] == 'claude-3-opus'
@@ -263,7 +261,7 @@ async def test_search_api_key_explicit_clear(test_client):
async def test_disabled_skills_persistence(test_client):
"""Test that disabled_skills can be saved and retrieved via the settings API."""
response = test_client.post(
- '/api/settings',
+ '/api/v1/settings',
json=_dump(
Settings(
disabled_skills=['skill_a', 'skill_b'],
@@ -273,29 +271,29 @@ async def test_disabled_skills_persistence(test_client):
)
assert response.status_code == 200
- response = test_client.get('/api/settings')
+ response = test_client.get('/api/v1/settings')
assert response.status_code == 200
data = response.json()
assert data['disabled_skills'] == ['skill_a', 'skill_b']
response = test_client.post(
- '/api/settings',
+ '/api/v1/settings',
json=_dump(Settings(disabled_skills=['skill_c'])),
)
assert response.status_code == 200
- response = test_client.get('/api/settings')
+ response = test_client.get('/api/v1/settings')
assert response.status_code == 200
data = response.json()
assert data['disabled_skills'] == ['skill_c']
response = test_client.post(
- '/api/settings',
+ '/api/v1/settings',
json=_dump(Settings(disabled_skills=[])),
)
assert response.status_code == 200
- response = test_client.get('/api/settings')
+ response = test_client.get('/api/v1/settings')
assert response.status_code == 200
data = response.json()
assert data['disabled_skills'] == []
diff --git a/tests/unit/events/test_contextual_events.py b/tests/unit/events/test_contextual_events.py
deleted file mode 100644
index 6f8fc9b31c..0000000000
--- a/tests/unit/events/test_contextual_events.py
+++ /dev/null
@@ -1,540 +0,0 @@
-from unittest.mock import MagicMock
-
-from openhands.events.action import (
- Action,
- ChangeAgentStateAction,
- CmdRunAction,
- MessageAction,
- NullAction,
-)
-from openhands.events.event import Event, EventSource
-from openhands.events.event_filter import (
- EventFilter, # Needed for ANY matcher type check
-)
-from openhands.events.observation import (
- AgentStateChangedObservation,
- CmdOutputObservation,
- NullObservation,
-)
-from openhands.events.stream import EventStream
-from openhands.server.routes.manage_conversations import _get_contextual_events
-
-
-# Helper to create event instances for testing, inspired by test_agent_history.py
-def create_test_events(event_specs: list[dict]) -> list[Event]:
- events = []
- for spec in event_specs:
- event_type = spec['type']
- # Attributes for the constructor
- kwargs = {
- k: v
- for k, v in spec.items()
- if k not in ['type', 'id', 'source', 'hidden', 'cause']
- }
-
- # Provide default values for required fields if not in spec, to ensure instantiation
- if event_type == MessageAction and 'content' not in kwargs:
- kwargs['content'] = f'default_content_for_{spec["id"]}'
- elif event_type == CmdRunAction and 'command' not in kwargs:
- kwargs['command'] = f'default_command_for_{spec["id"]}'
- elif event_type == CmdOutputObservation:
- if 'content' not in kwargs:
- kwargs['content'] = f'default_obs_content_for_{spec["id"]}'
- if 'command_id' not in kwargs:
- kwargs['command_id'] = spec.get(
- 'cause', spec['id'] - 1 if spec['id'] > 0 else 0
- ) # Simplistic default
- if 'command' not in kwargs:
- kwargs['command'] = f'default_cmd_for_obs_{spec["id"]}'
- elif event_type == NullAction:
- assert 'content' not in kwargs
- elif event_type == NullObservation:
- kwargs['content'] = ''
- elif event_type == ChangeAgentStateAction:
- if 'agent_state' not in kwargs:
- kwargs['agent_state'] = 'running'
- if 'thought' not in kwargs:
- kwargs['thought'] = ''
- # 'content' for ChangeAgentStateAction is auto-generated by its message property
- elif event_type == AgentStateChangedObservation:
- if 'agent_state' not in kwargs:
- kwargs['agent_state'] = 'running'
- # 'content' for AgentStateChangedObservation is auto-generated by its message property
-
- event = event_type(**kwargs)
-
- # Set internal attributes after instantiation
- event._id = spec['id']
- # Default source based on type, can be overridden by spec
- default_source = (
- EventSource.AGENT if issubclass(event_type, Action) else EventSource.USER
- )
- event._source = spec.get('source', default_source)
- event._hidden = spec.get('hidden', False)
- if 'cause' in spec:
- event._cause = spec['cause']
-
- events.append(event)
- return events
-
-
-def test_get_contextual_events_basic_retrieval():
- """Tests basic retrieval of events, ensuring correct count, order, and string formatting.
- All events in this test are of types that are NOT filtered out by default.
- """
- mock_event_stream = MagicMock(spec=EventStream)
- target_event_id = 5
- context_size = 4 # Hardcoded in _get_contextual_events
-
- # Define all events that *could* be in the stream for this test
- all_event_specs = [
- {'id': 1, 'type': MessageAction, 'content': 'message_1'},
- {'id': 2, 'type': CmdRunAction, 'command': 'command_2'},
- {
- 'id': 3,
- 'type': CmdOutputObservation,
- 'content': 'observation_3',
- 'command_id': 2,
- 'command': 'command_2',
- },
- {'id': 4, 'type': MessageAction, 'content': 'message_4'},
- {'id': 5, 'type': CmdRunAction, 'command': 'command_5_target'}, # Target Event
- {
- 'id': 6,
- 'type': CmdOutputObservation,
- 'content': 'observation_6',
- 'command_id': 5,
- 'command': 'command_5_target',
- },
- {'id': 7, 'type': MessageAction, 'content': 'message_7'},
- {'id': 8, 'type': CmdRunAction, 'command': 'command_8'},
- {
- 'id': 9,
- 'type': CmdOutputObservation,
- 'content': 'observation_9',
- 'command_id': 8,
- 'command': 'command_8',
- },
- {'id': 10, 'type': MessageAction, 'content': 'message_10'},
- {
- 'id': 11,
- 'type': CmdRunAction,
- 'command': 'command_11',
- }, # Extra event, should not be included in 'after' due to limit
- ]
- all_events_objects = create_test_events(all_event_specs)
-
- # Map IDs to objects for easy lookup
- events_by_id = {e.id: e for e in all_events_objects}
-
- # Define what search_events should return for the "before" call
- # (event_id=5, limit=4, reverse=True) -> expects [5, 4, 3, 2]
- events_to_return_before = [
- events_by_id[5],
- events_by_id[4],
- events_by_id[3],
- events_by_id[2],
- ]
-
- # Define what search_events should return for the "after" call
- # (start_id=6, limit=5) -> expects [6, 7, 8, 9, 10]
- events_to_return_after = [
- events_by_id[6],
- events_by_id[7],
- events_by_id[8],
- events_by_id[9],
- events_by_id[10],
- ]
-
- mock_event_stream.search_events.side_effect = [
- events_to_return_before,
- events_to_return_after,
- ]
-
- result_str = _get_contextual_events(mock_event_stream, target_event_id)
-
- # Expected final list of events after processing (chronological order):
- # [event_obj_2, event_obj_3, event_obj_4, event_obj_5, (from before, reversed)
- # event_obj_6, event_obj_7, event_obj_8, event_obj_9, event_obj_10 (from after)]
- expected_final_event_objects = [
- events_by_id[2],
- events_by_id[3],
- events_by_id[4],
- events_by_id[5],
- events_by_id[6],
- events_by_id[7],
- events_by_id[8],
- events_by_id[9],
- events_by_id[10],
- ]
-
- # The output string is joined by newlines, using event.__str__
- expected_output_str = '\n'.join(str(e) for e in expected_final_event_objects)
-
- assert result_str == expected_output_str
-
- # Check calls to search_events
- calls = mock_event_stream.search_events.call_args_list
- assert len(calls) == 2
-
- # Call 1: Before events
- args_before, kwargs_before = calls[0]
- assert kwargs_before['start_id'] == target_event_id
- assert isinstance(kwargs_before['filter'], EventFilter)
- assert kwargs_before['reverse'] is True
- assert kwargs_before['limit'] == context_size
-
- # Call 2: After events
- args_after, kwargs_after = calls[1]
- assert kwargs_after['start_id'] == target_event_id + 1
- assert isinstance(kwargs_after['filter'], EventFilter)
- assert (
- 'reverse' not in kwargs_after or kwargs_after['reverse'] is False
- ) # default is False
- assert kwargs_after['limit'] == context_size + 1
-
-
-def test_get_contextual_events_filtering():
- """Tests that specified event types and hidden events are filtered out."""
- mock_event_stream = MagicMock(spec=EventStream)
- target_event_id = 3 # Target a non-filtered event
-
- all_event_specs = [
- # Before target_event_id = 3. Context size 4. Search limit 4.
- # search_events(start_id=3, reverse=True, limit=4)
- {'id': 0, 'type': NullAction}, # Filtered
- {'id': 1, 'type': MessageAction, 'content': 'message_1_VISIBLE'}, # Visible
- {
- 'id': 2,
- 'type': ChangeAgentStateAction,
- 'agent_state': 'thinking',
- 'thought': 'abc_FILTERED',
- }, # Filtered
- {
- 'id': 3,
- 'type': CmdRunAction,
- 'command': 'command_3_TARGET_VISIBLE',
- }, # Target, Visible
- # After target_event_id = 3. Context size 4 + 1 = 5. Search limit 5.
- # search_events(start_id=4, limit=5)
- {
- 'id': 4,
- 'type': CmdOutputObservation,
- 'content': 'obs_4_HIDDEN_FILTERED',
- 'command_id': 3,
- 'hidden': True,
- }, # Filtered (hidden)
- {
- 'id': 5,
- 'type': AgentStateChangedObservation,
- 'agent_state': 'running',
- 'content': 'state_change_5_FILTERED',
- }, # Filtered
- {'id': 6, 'type': MessageAction, 'content': 'message_6_VISIBLE'}, # Visible
- {
- 'id': 7,
- 'type': NullObservation,
- 'content': 'null_obs_7_FILTERED',
- }, # Filtered
- {'id': 8, 'type': CmdRunAction, 'command': 'command_8_VISIBLE'}, # Visible
- {
- 'id': 9,
- 'type': MessageAction,
- 'content': 'message_9_VISIBLE',
- }, # Visible (within limit of 5 for 'after' search)
- {
- 'id': 10,
- 'type': MessageAction,
- 'content': 'message_10_EXTRA',
- }, # Extra, should not be fetched by 'after' search
- ]
- all_events_objects = create_test_events(all_event_specs)
- events_by_id = {e.id: e for e in all_events_objects}
-
- # Expected events to be returned by search_events AFTER internal filtering by EventFilter
- # For "before" call (start_id=3, reverse=True, limit=4):
- # Raw available before/incl target: [cmd3, state2_filt, msg1, null0_filt]
- # After EventFilter: [cmd3, msg1] -> search_events should return these
- [events_by_id[3], events_by_id[1]]
-
- # For "after" call (start_id=4, limit=5):
- # Raw available after target: [hidden_obs4_filt, agent_state5_filt, msg6, null_obs7_filt, cmd8, msg9, msg10_extra]
- # After EventFilter: [msg6, cmd8, msg9, msg10_extra] -> search_events should return first 5 of these if available
- # Limit is 5, so it should return [msg6, cmd8, msg9] (msg10_extra is out of original context_size+1 scope)
- # Correcting this: the mock search_events should simulate what EventStream.search_events does.
- # EventStream.search_events applies the filter internally.
- # So, the lists passed to side_effect should be the *already filtered* lists.
-
- # Simulating EventStream.search_events behavior:
- # It iterates, applies filter, then takes limit.
-
- # Before: start_id=3, reverse=True, limit=4. Candidates: [3,2,1,0]. Filtered: [3,1]. Result: [3,1]
- simulated_search_before = [events_by_id[3], events_by_id[1]]
-
- # After: start_id=4, limit=5. Candidates: [4,5,6,7,8,9,10]. Filtered: [6,8,9]. Result: [6,8,9]
- simulated_search_after = [events_by_id[6], events_by_id[8], events_by_id[9]]
-
- mock_event_stream.search_events.side_effect = [
- simulated_search_before,
- simulated_search_after,
- ]
-
- result_str = _get_contextual_events(mock_event_stream, target_event_id)
-
- expected_final_event_objects = [
- events_by_id[1], # from before, reversed
- events_by_id[3], # from before, reversed (target)
- events_by_id[6], # from after
- events_by_id[8], # from after
- events_by_id[9], # from after
- ]
- expected_output_str = '\n'.join(str(e) for e in expected_final_event_objects)
-
- assert result_str == expected_output_str
-
- # Verify the EventFilter used in search_events
- calls = mock_event_stream.search_events.call_args_list
- assert len(calls) == 2
-
- expected_filtered_types = (
- NullAction,
- NullObservation,
- ChangeAgentStateAction,
- AgentStateChangedObservation,
- )
-
- # Check filter for "before" call
- filter_before = calls[0][1]['filter'] # kwargs['filter']
- assert isinstance(filter_before, EventFilter)
- assert filter_before.exclude_hidden is True
- assert set(filter_before.exclude_types) == set(expected_filtered_types)
-
- # Check filter for "after" call
- filter_after = calls[1][1]['filter'] # kwargs['filter']
- assert isinstance(filter_after, EventFilter)
- assert filter_after.exclude_hidden is True
- assert set(filter_after.exclude_types) == set(expected_filtered_types)
-
-
-def test_get_contextual_events_target_at_beginning():
- """Tests behavior when the target event_id is at the beginning of the stream,
- resulting in fewer than context_size events before it.
- """
- mock_event_stream = MagicMock(spec=EventStream)
- target_event_id = 1 # Target is the second event (IDs are 0-indexed in list, 1-indexed for events)
- context_size = 4
-
- all_event_specs = [
- {'id': 0, 'type': MessageAction, 'content': 'message_0_first'},
- {'id': 1, 'type': CmdRunAction, 'command': 'command_1_TARGET'}, # Target
- {'id': 2, 'type': CmdOutputObservation, 'content': 'obs_2', 'command_id': 1},
- {'id': 3, 'type': MessageAction, 'content': 'message_3'},
- {'id': 4, 'type': CmdRunAction, 'command': 'command_4'},
- {'id': 5, 'type': CmdOutputObservation, 'content': 'obs_5', 'command_id': 4},
- {
- 'id': 6,
- 'type': MessageAction,
- 'content': 'message_6',
- }, # Should be fetched by 'after'
- ]
- all_events_objects = create_test_events(all_event_specs)
- events_by_id = {e.id: e for e in all_events_objects}
-
- # Before: start_id=1, reverse=True, limit=4. Candidates: [1,0]. Filtered: [1,0]. Result: [1,0]
- simulated_search_before = [events_by_id[1], events_by_id[0]]
-
- # After: start_id=2, limit=5. Candidates: [2,3,4,5,6]. Filtered: [2,3,4,5,6]. Result: [2,3,4,5,6]
- simulated_search_after = [
- events_by_id[2],
- events_by_id[3],
- events_by_id[4],
- events_by_id[5],
- events_by_id[6],
- ]
-
- mock_event_stream.search_events.side_effect = [
- simulated_search_before,
- simulated_search_after,
- ]
-
- result_str = _get_contextual_events(mock_event_stream, target_event_id)
-
- # Expected final: [event_obj_0, event_obj_1] (from before, reversed)
- # + [event_obj_2, event_obj_3, event_obj_4, event_obj_5, event_obj_6] (from after)
- expected_final_event_objects = [
- events_by_id[0],
- events_by_id[1],
- events_by_id[2],
- events_by_id[3],
- events_by_id[4],
- events_by_id[5],
- events_by_id[6],
- ]
- expected_output_str = '\n'.join(str(e) for e in expected_final_event_objects)
-
- assert result_str == expected_output_str
-
- calls = mock_event_stream.search_events.call_args_list
- assert len(calls) == 2
- # Call 1: Before events
- kwargs_before = calls[0][1]
- assert kwargs_before['start_id'] == target_event_id
- assert kwargs_before['limit'] == context_size
- # Call 2: After events
- kwargs_after = calls[1][1]
- assert kwargs_after['start_id'] == target_event_id + 1
- assert kwargs_after['limit'] == context_size + 1
-
-
-def test_get_contextual_events_target_at_end():
- """Tests behavior when the target event_id is at the end of the stream,
- resulting in fewer than context_size + 1 events after it.
- """
- mock_event_stream = MagicMock(spec=EventStream)
- target_event_id = 5 # Target is near the end
- context_size = 4
-
- all_event_specs = [
- {'id': 0, 'type': MessageAction, 'content': 'message_0'},
- {'id': 1, 'type': CmdRunAction, 'command': 'command_1'},
- {
- 'id': 2,
- 'type': CmdOutputObservation,
- 'content': 'obs_2',
- 'command_id': 1,
- }, # Fetched by 'before'
- {'id': 3, 'type': MessageAction, 'content': 'message_3'}, # Fetched by 'before'
- {'id': 4, 'type': CmdRunAction, 'command': 'command_4'}, # Fetched by 'before'
- {
- 'id': 5,
- 'type': CmdOutputObservation,
- 'content': 'obs_5_TARGET',
- 'command_id': 4,
- }, # Target, Fetched by 'before'
- {
- 'id': 6,
- 'type': MessageAction,
- 'content': 'message_6_last',
- }, # Last event, fetched by 'after'
- ]
- all_events_objects = create_test_events(all_event_specs)
- events_by_id = {e.id: e for e in all_events_objects}
-
- # Before: start_id=5, reverse=True, limit=4.
- # Candidates (reverse chronological from stream): [5,4,3,2,1,0]
- # search_events (after its internal filtering, assuming all visible) should return: [events_by_id[5], events_by_id[4], events_by_id[3], events_by_id[2]]
- simulated_search_before = [
- events_by_id[5],
- events_by_id[4],
- events_by_id[3],
- events_by_id[2],
- ]
-
- # After: start_id=6, limit=context_size + 1 = 5.
- # Candidates from stream: [events_by_id[6]]
- # search_events (after its internal filtering) should return: [events_by_id[6]]
- simulated_search_after = [events_by_id[6]]
-
- mock_event_stream.search_events.side_effect = [
- simulated_search_before,
- simulated_search_after,
- ]
-
- result_str = _get_contextual_events(mock_event_stream, target_event_id)
-
- # Expected final:
- # From 'before' (reversed): [event_obj_2, event_obj_3, event_obj_4, event_obj_5]
- # From 'after': [event_obj_6]
- expected_final_event_objects = [
- events_by_id[2],
- events_by_id[3],
- events_by_id[4],
- events_by_id[5],
- events_by_id[6],
- ]
- expected_output_str = '\n'.join(str(e) for e in expected_final_event_objects)
-
- assert result_str == expected_output_str
-
- calls = mock_event_stream.search_events.call_args_list
- assert len(calls) == 2
- kwargs_before = calls[0][1]
- assert kwargs_before['start_id'] == target_event_id
- assert kwargs_before['limit'] == context_size # context_size for before
- kwargs_after = calls[1][1]
- assert kwargs_after['start_id'] == target_event_id + 1
- assert kwargs_after['limit'] == context_size + 1 # context_size + 1 for after
-
-
-def test_get_contextual_events_empty_search_results():
- """Tests behavior when search_events returns empty lists for before and after."""
- mock_event_stream = MagicMock(spec=EventStream)
- target_event_id = 10
- context_size = 4
-
- # search_events will return empty lists
- simulated_search_before = []
- simulated_search_after = []
-
- mock_event_stream.search_events.side_effect = [
- simulated_search_before,
- simulated_search_after,
- ]
-
- result_str = _get_contextual_events(mock_event_stream, target_event_id)
-
- expected_output_str = '' # Empty string as no events are found
-
- assert result_str == expected_output_str
-
- calls = mock_event_stream.search_events.call_args_list
- assert len(calls) == 2
- kwargs_before = calls[0][1]
- assert kwargs_before['start_id'] == target_event_id
- assert kwargs_before['limit'] == context_size
- kwargs_after = calls[1][1]
- assert kwargs_after['start_id'] == target_event_id + 1
- assert kwargs_after['limit'] == context_size + 1
-
-
-def test_get_contextual_events_all_events_filtered():
- """Tests behavior when all events in the context window are of types
- that should be filtered out.
- """
- mock_event_stream = MagicMock(spec=EventStream)
- target_event_id = (
- 2 # Target event itself might be filtered or not, doesn't matter for this test
- )
-
- # All events are of types that should be filtered by the default filter in _get_contextual_events
- # create_test_events(all_event_specs) # Not strictly needed as search_events will return []
-
- # search_events, after applying the internal EventFilter, will return empty lists
- simulated_search_before = []
- simulated_search_after = []
-
- mock_event_stream.search_events.side_effect = [
- simulated_search_before,
- simulated_search_after,
- ]
-
- result_str = _get_contextual_events(mock_event_stream, target_event_id)
-
- expected_output_str = '' # Empty string as all events are filtered
-
- assert result_str == expected_output_str
-
- calls = mock_event_stream.search_events.call_args_list
- assert len(calls) == 2 # Still called twice
-
- # Check the filter properties on one of the calls (they should be identical)
- filter_used = calls[0][1]['filter']
- expected_filtered_types = (
- NullAction,
- NullObservation,
- ChangeAgentStateAction,
- AgentStateChangedObservation,
- )
- assert isinstance(filter_used, EventFilter)
- assert filter_used.exclude_hidden is True
- assert set(filter_used.exclude_types) == set(expected_filtered_types)
diff --git a/tests/unit/server/data_models/test_conversation.py b/tests/unit/server/data_models/test_conversation.py
deleted file mode 100644
index bef88a7b89..0000000000
--- a/tests/unit/server/data_models/test_conversation.py
+++ /dev/null
@@ -1,3425 +0,0 @@
-import json
-import uuid
-from contextlib import contextmanager
-from datetime import datetime, timezone
-from types import MappingProxyType
-from unittest.mock import AsyncMock, MagicMock, patch
-from uuid import uuid4
-
-import pytest
-from fastapi import FastAPI
-from fastapi.responses import JSONResponse
-from fastapi.testclient import TestClient
-
-from openhands.app_server.app_conversation.app_conversation_models import (
- AppConversation,
- AppConversationPage,
-)
-from openhands.app_server.app_conversation.app_conversation_router import (
- read_conversation_file,
-)
-from openhands.app_server.app_conversation.live_status_app_conversation_service import (
- LiveStatusAppConversationService,
-)
-from openhands.app_server.app_conversation.sql_app_conversation_info_service import (
- SQLAppConversationInfoService,
-)
-from openhands.app_server.sandbox.sandbox_models import (
- AGENT_SERVER,
- ExposedUrl,
- SandboxInfo,
- SandboxStatus,
-)
-from openhands.app_server.sandbox.sandbox_spec_models import SandboxSpecInfo
-from openhands.app_server.user.user_context import UserContext
-from openhands.integrations.service_types import (
- AuthenticationError,
- CreateMicroagent,
- ProviderType,
- SuggestedTask,
- TaskType,
-)
-from openhands.runtime.runtime_status import RuntimeStatus
-from openhands.sdk.conversation import ConversationExecutionStatus
-from openhands.sdk.workspace import FileOperationResult
-from openhands.sdk.workspace.remote.async_remote_workspace import (
- AsyncRemoteWorkspace,
-)
-from openhands.server.data_models.conversation_info import ConversationInfo
-from openhands.server.data_models.conversation_info_result_set import (
- ConversationInfoResultSet,
-)
-from openhands.server.routes.manage_conversations import (
- ConversationResponse,
- InitSessionRequest,
- delete_conversation,
- get_conversation,
- new_conversation,
- search_conversations,
-)
-from openhands.server.routes.manage_conversations import app as conversation_app
-from openhands.server.types import LLMAuthenticationError, MissingSettingsError
-from openhands.server.user_auth.user_auth import AuthType
-from openhands.storage.data_models.conversation_metadata import (
- ConversationMetadata,
- ConversationTrigger,
-)
-from openhands.storage.data_models.conversation_status import ConversationStatus
-from openhands.storage.locations import get_conversation_metadata_filename
-from openhands.storage.memory import InMemoryFileStore
-
-
-@contextmanager
-def _patch_store():
- file_store = InMemoryFileStore()
- file_store.write(
- get_conversation_metadata_filename('some_conversation_id'),
- json.dumps(
- {
- 'title': 'Some ServerConversation',
- 'selected_repository': 'foobar',
- 'conversation_id': 'some_conversation_id',
- 'user_id': '12345',
- 'created_at': '2025-01-01T00:00:00+00:00',
- 'last_updated_at': '2025-01-01T00:01:00+00:00',
- }
- ),
- )
- with patch(
- 'openhands.storage.conversation.file_conversation_store.get_file_store',
- MagicMock(return_value=file_store),
- ):
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager.file_store',
- file_store,
- ):
- yield
-
-
-def test_client():
- """Create a test client for the settings API."""
- app = FastAPI()
- app.include_router(conversation_app)
- return TestClient(app)
-
-
-def create_new_test_conversation(
- test_request: InitSessionRequest, auth_type: AuthType | None = None
-):
- # Create a mock Secrets object with the required custom_secrets attribute
- mock_user_secrets = MagicMock()
- mock_user_secrets.custom_secrets = MappingProxyType({})
-
- return new_conversation(
- data=test_request,
- user_id='test_user',
- provider_tokens=MappingProxyType({'github': 'token123'}),
- user_secrets=mock_user_secrets,
- auth_type=auth_type,
- )
-
-
-def provider_handler_mock():
- with patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler'
- ) as mock_cls:
- mock_instance = MagicMock()
- mock_instance.verify_repo_provider = AsyncMock(return_value=ProviderType.GITHUB)
- mock_cls.return_value = mock_instance
- yield mock_instance
-
-
-async def test_search_conversations():
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='some_conversation_id',
- title='Some ServerConversation',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='foobar',
- user_id='12345',
- )
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- expected = ConversationInfoResultSet(
- results=[
- ConversationInfo(
- conversation_id='some_conversation_id',
- title='Some ServerConversation',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- status=ConversationStatus.STOPPED,
- selected_repository='foobar',
- num_connections=0,
- url=None,
- pr_number=[], # Default empty list for pr_number
- )
- ]
- )
- assert result_set == expected
-
-
-async def test_search_conversations_with_repository_filter():
- """Test searching conversations with repository filter."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_1',
- title='Conversation 1',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- )
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository='test/repo',
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search was called with only pagination parameters (filtering is done at API level)
- mock_store.search.assert_called_once_with(None, 20)
-
- # Verify the result contains only conversations from the specified repository
- assert len(result_set.results) == 1
- assert result_set.results[0].selected_repository == 'test/repo'
-
-
-async def test_search_conversations_with_trigger_filter():
- """Test searching conversations with conversation trigger filter."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_1',
- title='Conversation 1',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- trigger=ConversationTrigger.GUI,
- user_id='12345',
- )
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=ConversationTrigger.GUI,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search was called with only pagination parameters (filtering is done at API level)
- mock_store.search.assert_called_once_with(None, 20)
-
- # Verify the result contains only conversations with the specified trigger
- assert len(result_set.results) == 1
- assert result_set.results[0].trigger == ConversationTrigger.GUI
-
-
-async def test_search_conversations_with_both_filters():
- """Test searching conversations with both repository and trigger filters."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_1',
- title='Conversation 1',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- trigger=ConversationTrigger.SUGGESTED_TASK,
- user_id='12345',
- )
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository='test/repo',
- conversation_trigger=ConversationTrigger.SUGGESTED_TASK,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search was called with only pagination parameters (filtering is done at API level)
- mock_store.search.assert_called_once_with(None, 20)
-
- # Verify the result contains only conversations matching both filters
- assert len(result_set.results) == 1
- result = result_set.results[0]
- assert result.selected_repository == 'test/repo'
- assert result.trigger == ConversationTrigger.SUGGESTED_TASK
-
-
-async def test_search_conversations_with_pagination():
- """Test searching conversations with pagination."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_1',
- title='Conversation 1',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- )
- ],
- next_page_id='next_page_123',
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id='eyJ2MCI6ICJwYWdlXzEyMyIsICJ2MSI6IG51bGx9',
- limit=10,
- selected_repository=None,
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search was called with pagination parameters (filtering is done at API level)
- mock_store.search.assert_called_once_with('page_123', 10)
-
- # Verify the result includes pagination info
- assert (
- result_set.next_page_id
- == 'eyJ2MCI6ICJuZXh0X3BhZ2VfMTIzIiwgInYxIjogbnVsbH0='
- )
-
-
-async def test_search_conversations_with_filters_and_pagination():
- """Test searching conversations with filters and pagination."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_1',
- title='Conversation 1',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- trigger=ConversationTrigger.GUI,
- user_id='12345',
- )
- ],
- next_page_id='next_page_456',
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id='eyJ2MCI6ICJwYWdlXzQ1NiIsICJ2MSI6IG51bGx9',
- limit=5,
- selected_repository='test/repo',
- conversation_trigger=ConversationTrigger.GUI,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search was called with only pagination parameters (filtering is done at API level)
- mock_store.search.assert_called_once_with('page_456', 5)
-
- # Verify the result includes pagination info
- assert (
- result_set.next_page_id
- == 'eyJ2MCI6ICJuZXh0X3BhZ2VfNDU2IiwgInYxIjogbnVsbH0='
- )
- assert len(result_set.results) == 1
- result = result_set.results[0]
- assert result.selected_repository == 'test/repo'
- assert result.trigger == ConversationTrigger.GUI
-
-
-async def test_search_conversations_empty_results():
- """Test searching conversations that returns empty results."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[], next_page_id=None
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository='nonexistent/repo',
- conversation_trigger=ConversationTrigger.GUI,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search was called with only pagination parameters (filtering is done at API level)
- mock_store.search.assert_called_once_with(None, 20)
-
- # Verify the result is empty
- assert len(result_set.results) == 0
- assert result_set.next_page_id is None
-
-
-async def test_get_conversation():
- with _patch_store():
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.get_metadata = AsyncMock(
- return_value=ConversationMetadata(
- conversation_id='some_conversation_id',
- title='Some ServerConversation',
- created_at=datetime.fromisoformat('2025-01-01T00:00:00+00:00'),
- last_updated_at=datetime.fromisoformat('2025-01-01T00:01:00+00:00'),
- selected_repository='foobar',
- user_id='12345',
- )
- )
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.is_agent_loop_running = AsyncMock(return_value=False)
- mock_manager.get_connections = AsyncMock(return_value={})
- mock_manager.get_agent_loop_info = AsyncMock(return_value=[])
-
- conversation = await get_conversation(
- 'some_conversation_id', conversation_store=mock_store
- )
-
- expected = ConversationInfo(
- conversation_id='some_conversation_id',
- title='Some ServerConversation',
- created_at=datetime.fromisoformat('2025-01-01T00:00:00+00:00'),
- last_updated_at=datetime.fromisoformat('2025-01-01T00:01:00+00:00'),
- status=ConversationStatus.STOPPED,
- selected_repository='foobar',
- num_connections=0,
- url=None,
- pr_number=[], # Default empty list for pr_number
- )
- assert conversation == expected
-
-
-async def test_get_missing_conversation():
- with _patch_store():
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.get_metadata = AsyncMock(side_effect=FileNotFoundError)
-
- assert (
- await get_conversation(
- 'no_such_conversation', conversation_store=mock_store
- )
- is None
- )
-
-
-async def test_new_conversation_success(provider_handler_mock):
- """Test successful creation of a new conversation."""
- with _patch_store():
- # Mock the create_new_conversation function directly
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = MagicMock(
- conversation_id='test_conversation_id',
- url='https://my-conversation.com',
- session_api_key=None,
- status=ConversationStatus.RUNNING,
- )
-
- test_request = InitSessionRequest(
- repository='test/repo',
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- image_urls=['https://example.com/image.jpg'],
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, ConversationResponse)
- assert response.status == 'ok'
- # Don't check the exact conversation_id as it's now generated dynamically
- assert response.conversation_id is not None
- assert isinstance(response.conversation_id, str)
-
- # Verify that create_new_conversation was called with the correct arguments
- mock_create_conversation.assert_called_once()
- call_args = mock_create_conversation.call_args[1]
- assert call_args['user_id'] == 'test_user'
- assert call_args['selected_repository'] == 'test/repo'
- assert call_args['selected_branch'] == 'main'
- assert call_args['initial_user_msg'] == 'Hello, agent!'
- assert call_args['image_urls'] == ['https://example.com/image.jpg']
- assert call_args['conversation_trigger'] == ConversationTrigger.GUI
-
-
-async def test_new_conversation_with_suggested_task(provider_handler_mock):
- """Test creating a new conversation with a suggested task."""
- with _patch_store():
- # Mock the create_new_conversation function directly
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = MagicMock(
- conversation_id='test_conversation_id',
- url='https://my-conversation.com',
- session_api_key=None,
- status=ConversationStatus.RUNNING,
- )
-
- # Mock SuggestedTask.get_prompt_for_task
- with patch(
- 'openhands.integrations.service_types.SuggestedTask.get_prompt_for_task'
- ) as mock_get_prompt:
- mock_get_prompt.return_value = (
- 'Please fix the failing checks in PR #123'
- )
-
- test_task = SuggestedTask(
- git_provider=ProviderType.GITHUB,
- task_type=TaskType.FAILING_CHECKS,
- repo='test/repo',
- issue_number=123,
- title='Fix failing checks',
- )
-
- test_request = InitSessionRequest(
- repository='test/repo',
- selected_branch='main',
- suggested_task=test_task,
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, ConversationResponse)
- assert response.status == 'ok'
- # Don't check the exact conversation_id as it's now generated dynamically
- assert response.conversation_id is not None
- assert isinstance(response.conversation_id, str)
-
- # Verify that create_new_conversation was called with the correct arguments
- mock_create_conversation.assert_called_once()
- call_args = mock_create_conversation.call_args[1]
- assert call_args['user_id'] == 'test_user'
- assert call_args['selected_repository'] == 'test/repo'
- assert call_args['selected_branch'] == 'main'
- assert (
- call_args['initial_user_msg']
- == 'Please fix the failing checks in PR #123'
- )
- assert (
- call_args['conversation_trigger']
- == ConversationTrigger.SUGGESTED_TASK
- )
-
- # Verify that get_prompt_for_task was called
- mock_get_prompt.assert_called_once()
-
-
-async def test_new_conversation_missing_settings(provider_handler_mock):
- """Test creating a new conversation when settings are missing."""
- with _patch_store():
- # Mock the create_new_conversation function to raise MissingSettingsError
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to raise MissingSettingsError
- mock_create_conversation.side_effect = MissingSettingsError(
- 'Settings not found'
- )
-
- test_request = InitSessionRequest(
- repository='test/repo',
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 400
- assert 'Settings not found' in response.body.decode('utf-8')
- assert 'CONFIGURATION$SETTINGS_NOT_FOUND' in response.body.decode('utf-8')
-
-
-async def test_new_conversation_invalid_session_api_key(provider_handler_mock):
- """Test creating a new conversation with an invalid API key."""
- with _patch_store():
- # Mock the create_new_conversation function to raise LLMAuthenticationError
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to raise LLMAuthenticationError
- mock_create_conversation.side_effect = LLMAuthenticationError(
- 'Error authenticating with the LLM provider. Please check your API key'
- )
-
- test_request = InitSessionRequest(
- repository='test/repo',
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 400
- assert 'Error authenticating with the LLM provider' in response.body.decode(
- 'utf-8'
- )
- assert RuntimeStatus.ERROR_LLM_AUTHENTICATION.value in response.body.decode(
- 'utf-8'
- )
-
-
-async def test_delete_conversation():
- with _patch_store():
- # Mock the ConversationStoreImpl.get_instance
- with patch(
- 'openhands.server.routes.manage_conversations.ConversationStoreImpl.get_instance'
- ) as mock_get_instance:
- # Create a mock conversation store
- mock_store = MagicMock()
-
- # Set up the mock to return metadata and then delete it
- mock_store.get_metadata = AsyncMock(
- return_value=ConversationMetadata(
- conversation_id='some_conversation_id',
- title='Some ServerConversation',
- created_at=datetime.fromisoformat('2025-01-01T00:00:00+00:00'),
- last_updated_at=datetime.fromisoformat('2025-01-01T00:01:00+00:00'),
- selected_repository='foobar',
- user_id='12345',
- )
- )
- mock_store.delete_metadata = AsyncMock()
-
- # Return the mock store from get_instance
- mock_get_instance.return_value = mock_store
-
- # Create a mock app conversation service
- mock_app_conversation_service = MagicMock()
-
- # Create a mock app conversation info service
- mock_app_conversation_info_service = MagicMock()
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=None
- )
-
- # Create a mock sandbox service
- mock_sandbox_service = MagicMock()
-
- # Create mock db_session and httpx_client
- mock_db_session = AsyncMock()
- mock_httpx_client = AsyncMock()
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.is_agent_loop_running = AsyncMock(return_value=False)
- mock_manager.get_connections = AsyncMock(return_value={})
-
- # Mock the runtime class
- with patch(
- 'openhands.server.routes.manage_conversations.get_runtime_cls'
- ) as mock_get_runtime_cls:
- mock_runtime_cls = MagicMock()
- mock_runtime_cls.delete = AsyncMock()
- mock_get_runtime_cls.return_value = mock_runtime_cls
-
- # Call delete_conversation
- result = await delete_conversation(
- request=MagicMock(),
- conversation_id='some_conversation_id',
- user_id='12345',
- app_conversation_service=mock_app_conversation_service,
- app_conversation_info_service=mock_app_conversation_info_service,
- sandbox_service=mock_sandbox_service,
- db_session=mock_db_session,
- httpx_client=mock_httpx_client,
- )
-
- # Verify the result
- assert result is True
-
- # Verify that delete_metadata was called
- mock_store.delete_metadata.assert_called_once_with(
- 'some_conversation_id'
- )
-
- # Verify that runtime.delete was called
- mock_runtime_cls.delete.assert_called_once_with(
- 'some_conversation_id'
- )
-
-
-async def test_delete_v1_conversation_success():
- """Test successful deletion of a V1 conversation."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
-
- # Mock the app conversation service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_service_dependency'
- ) as mock_service_dep:
- mock_service = MagicMock()
- mock_service_dep.return_value = mock_service
-
- # Mock the app conversation info service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_info_service_dependency'
- ) as mock_info_service_dep:
- mock_info_service = MagicMock()
- mock_info_service_dep.return_value = mock_info_service
-
- # Mock the sandbox service
- with patch(
- 'openhands.server.routes.manage_conversations.sandbox_service_dependency'
- ) as mock_sandbox_service_dep:
- mock_sandbox_service = MagicMock()
- mock_sandbox_service_dep.return_value = mock_sandbox_service
-
- # Mock the conversation info exists
- mock_app_conversation_info = AppConversation(
- id=conversation_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test V1 Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
- mock_info_service.get_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
- mock_service.delete_app_conversation = AsyncMock(return_value=True)
- mock_info_service.count_conversations_by_sandbox_id = AsyncMock(
- return_value=1
- )
-
- # Call delete_conversation with V1 conversation ID
- result = await delete_conversation(
- request=MagicMock(),
- conversation_id=conversation_id,
- user_id='test_user',
- app_conversation_service=mock_service,
- app_conversation_info_service=mock_info_service,
- sandbox_service=mock_sandbox_service,
- )
-
- # Verify the result
- assert result is True
-
- # Verify that get_app_conversation_info was called
- mock_info_service.get_app_conversation_info.assert_called_once_with(
- conversation_uuid
- )
-
- # Verify that delete_app_conversation was called with the conversation ID
- mock_service.delete_app_conversation.assert_called_once_with(
- conversation_uuid,
- skip_agent_server_delete=False,
- )
-
-
-async def test_delete_v1_conversation_not_found():
- """Test deletion of a V1 conversation that doesn't exist."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
-
- # Mock the app conversation service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_service_dependency'
- ) as mock_service_dep:
- mock_service = MagicMock()
- mock_service_dep.return_value = mock_service
-
- # Mock the app conversation info service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_info_service_dependency'
- ) as mock_info_service_dep:
- mock_info_service = MagicMock()
- mock_info_service_dep.return_value = mock_info_service
-
- # Mock the sandbox service
- with patch(
- 'openhands.server.routes.manage_conversations.sandbox_service_dependency'
- ) as mock_sandbox_service_dep:
- mock_sandbox_service = MagicMock()
- mock_sandbox_service_dep.return_value = mock_sandbox_service
-
- # Mock the conversation doesn't exist
- mock_info_service.get_app_conversation_info = AsyncMock(
- return_value=None
- )
- mock_service.delete_app_conversation = AsyncMock(return_value=False)
-
- # Create mock db_session and httpx_client
- mock_db_session = AsyncMock()
- mock_httpx_client = AsyncMock()
-
- # Call delete_conversation with V1 conversation ID
- result = await delete_conversation(
- request=MagicMock(),
- conversation_id=conversation_id,
- user_id='test_user',
- app_conversation_service=mock_service,
- app_conversation_info_service=mock_info_service,
- sandbox_service=mock_sandbox_service,
- db_session=mock_db_session,
- httpx_client=mock_httpx_client,
- )
-
- # Verify the result
- assert result is False
-
- # Verify that get_app_conversation_info was called
- mock_info_service.get_app_conversation_info.assert_called_once_with(
- conversation_uuid
- )
-
- # Verify that delete_app_conversation was NOT called
- mock_service.delete_app_conversation.assert_not_called()
-
-
-async def test_delete_v1_conversation_invalid_uuid():
- """Test deletion with invalid UUID falls back to V0 logic."""
- conversation_id = 'invalid-uuid-format'
-
- # Mock the app conversation service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_service_dependency'
- ) as mock_service_dep:
- mock_service = MagicMock()
- mock_service_dep.return_value = mock_service
-
- # Mock V0 conversation logic
- with patch(
- 'openhands.server.routes.manage_conversations.ConversationStoreImpl.get_instance'
- ) as mock_get_instance:
- mock_store = MagicMock()
- mock_store.get_metadata = AsyncMock(
- return_value=ConversationMetadata(
- conversation_id=conversation_id,
- title='Test V0 Conversation',
- created_at=datetime.fromisoformat('2025-01-01T00:00:00+00:00'),
- last_updated_at=datetime.fromisoformat('2025-01-01T00:01:00+00:00'),
- selected_repository='test/repo',
- user_id='test_user',
- )
- )
- mock_store.delete_metadata = AsyncMock()
- mock_get_instance.return_value = mock_store
-
- # Mock conversation manager
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.is_agent_loop_running = AsyncMock(return_value=False)
- mock_manager.get_connections = AsyncMock(return_value={})
-
- # Mock runtime
- with patch(
- 'openhands.server.routes.manage_conversations.get_runtime_cls'
- ) as mock_get_runtime_cls:
- mock_runtime_cls = MagicMock()
- mock_runtime_cls.delete = AsyncMock()
- mock_get_runtime_cls.return_value = mock_runtime_cls
-
- # Mock the app conversation info service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_info_service_dependency'
- ) as mock_info_service_dep:
- mock_info_service = MagicMock()
- mock_info_service_dep.return_value = mock_info_service
-
- # Mock the sandbox service
- with patch(
- 'openhands.server.routes.manage_conversations.sandbox_service_dependency'
- ) as mock_sandbox_service_dep:
- mock_sandbox_service = MagicMock()
- mock_sandbox_service_dep.return_value = mock_sandbox_service
-
- # Create mock db_session and httpx_client
- mock_db_session = AsyncMock()
- mock_httpx_client = AsyncMock()
-
- # Call delete_conversation
- result = await delete_conversation(
- request=MagicMock(),
- conversation_id=conversation_id,
- user_id='test_user',
- app_conversation_service=mock_service,
- app_conversation_info_service=mock_info_service,
- sandbox_service=mock_sandbox_service,
- db_session=mock_db_session,
- httpx_client=mock_httpx_client,
- )
-
- # Verify the result
- assert result is True
-
- # Verify V0 logic was used
- mock_store.delete_metadata.assert_called_once_with(
- conversation_id
- )
- mock_runtime_cls.delete.assert_called_once_with(
- conversation_id
- )
-
-
-async def test_delete_v1_conversation_service_error():
- """Test deletion when app conversation service raises an error."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
-
- # Mock the app conversation service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_service_dependency'
- ) as mock_service_dep:
- mock_service = MagicMock()
- mock_service_dep.return_value = mock_service
-
- # Mock the app conversation info service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_info_service_dependency'
- ) as mock_info_service_dep:
- mock_info_service = MagicMock()
- mock_info_service_dep.return_value = mock_info_service
-
- # Mock the sandbox service
- with patch(
- 'openhands.server.routes.manage_conversations.sandbox_service_dependency'
- ) as mock_sandbox_service_dep:
- mock_sandbox_service = MagicMock()
- mock_sandbox_service_dep.return_value = mock_sandbox_service
-
- # Mock service error
- mock_info_service.get_app_conversation_info = AsyncMock(
- side_effect=Exception('Service error')
- )
-
- # Mock V0 conversation logic as fallback
- with patch(
- 'openhands.server.routes.manage_conversations.ConversationStoreImpl.get_instance'
- ) as mock_get_instance:
- mock_store = MagicMock()
- mock_store.get_metadata = AsyncMock(
- return_value=ConversationMetadata(
- conversation_id=conversation_id,
- title='Test V0 Conversation',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='test_user',
- )
- )
- mock_store.delete_metadata = AsyncMock()
- mock_get_instance.return_value = mock_store
-
- # Mock conversation manager
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.is_agent_loop_running = AsyncMock(
- return_value=False
- )
- mock_manager.get_connections = AsyncMock(return_value={})
-
- # Mock runtime
- with patch(
- 'openhands.server.routes.manage_conversations.get_runtime_cls'
- ) as mock_get_runtime_cls:
- mock_runtime_cls = MagicMock()
- mock_runtime_cls.delete = AsyncMock()
- mock_get_runtime_cls.return_value = mock_runtime_cls
-
- # Create mock db_session and httpx_client
- mock_db_session = AsyncMock()
- mock_httpx_client = AsyncMock()
-
- # Call delete_conversation
- result = await delete_conversation(
- request=MagicMock(),
- conversation_id=conversation_id,
- user_id='test_user',
- app_conversation_service=mock_service,
- app_conversation_info_service=mock_info_service,
- sandbox_service=mock_sandbox_service,
- db_session=mock_db_session,
- httpx_client=mock_httpx_client,
- )
-
- # Verify the result (should fallback to V0)
- assert result is True
-
- # Verify V0 logic was used
- mock_store.delete_metadata.assert_called_once_with(
- conversation_id
- )
- mock_runtime_cls.delete.assert_called_once_with(
- conversation_id
- )
-
-
-async def test_delete_v1_conversation_with_agent_server():
- """Test V1 conversation deletion with agent server integration."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
-
- # Mock the app conversation service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_service_dependency'
- ) as mock_service_dep:
- mock_service = MagicMock()
- mock_service_dep.return_value = mock_service
-
- # Mock the app conversation info service
- with patch(
- 'openhands.server.routes.manage_conversations.app_conversation_info_service_dependency'
- ) as mock_info_service_dep:
- mock_info_service = MagicMock()
- mock_info_service_dep.return_value = mock_info_service
-
- # Mock the sandbox service
- with patch(
- 'openhands.server.routes.manage_conversations.sandbox_service_dependency'
- ) as mock_sandbox_service_dep:
- mock_sandbox_service = MagicMock()
- mock_sandbox_service_dep.return_value = mock_sandbox_service
-
- # Mock the conversation exists with running sandbox
- mock_app_conversation_info = AppConversation(
- id=conversation_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test V1 Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
- mock_info_service.get_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
- mock_service.delete_app_conversation = AsyncMock(return_value=True)
- mock_info_service.count_conversations_by_sandbox_id = AsyncMock(
- return_value=1
- )
-
- # Call delete_conversation with V1 conversation ID
- result = await delete_conversation(
- request=MagicMock(),
- conversation_id=conversation_id,
- user_id='test_user',
- app_conversation_service=mock_service,
- app_conversation_info_service=mock_info_service,
- sandbox_service=mock_sandbox_service,
- )
-
- # Verify the result
- assert result is True
-
- # Verify that get_app_conversation_info was called
- mock_info_service.get_app_conversation_info.assert_called_once_with(
- conversation_uuid
- )
-
- # Verify that delete_app_conversation was called with the conversation ID
- mock_service.delete_app_conversation.assert_called_once_with(
- conversation_uuid,
- skip_agent_server_delete=False,
- )
-
-
-async def test_new_conversation_with_bearer_auth(provider_handler_mock):
- """Test creating a new conversation with bearer authentication."""
- with _patch_store():
- # Mock the create_new_conversation function
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = MagicMock(
- conversation_id='test_conversation_id',
- url='https://my-conversation.com',
- session_api_key=None,
- status=ConversationStatus.RUNNING,
- )
-
- # Create the request object
- test_request = InitSessionRequest(
- repository='test/repo',
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- )
-
- # Call new_conversation with auth_type=BEARER
- response = await create_new_test_conversation(test_request, AuthType.BEARER)
-
- # Verify the response
- assert isinstance(response, ConversationResponse)
- assert response.status == 'ok'
-
- # Verify that create_new_conversation was called with REMOTE_API_KEY trigger
- mock_create_conversation.assert_called_once()
- call_args = mock_create_conversation.call_args[1]
- assert (
- call_args['conversation_trigger'] == ConversationTrigger.REMOTE_API_KEY
- )
-
-
-async def test_new_conversation_with_null_repository():
- """Test creating a new conversation with null repository."""
- with _patch_store():
- # Mock the create_new_conversation function
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = MagicMock(
- conversation_id='test_conversation_id',
- url='https://my-conversation.com',
- session_api_key=None,
- status=ConversationStatus.RUNNING,
- )
-
- # Create the request object with null repository
- test_request = InitSessionRequest(
- repository=None, # Explicitly set to None
- selected_branch=None,
- initial_user_msg='Hello, agent!',
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, ConversationResponse)
- assert response.status == 'ok'
-
- # Verify that create_new_conversation was called with None repository
- mock_create_conversation.assert_called_once()
- call_args = mock_create_conversation.call_args[1]
- assert call_args['selected_repository'] is None
-
-
-async def test_new_conversation_with_provider_authentication_error(
- provider_handler_mock,
-):
- provider_handler_mock.verify_repo_provider = AsyncMock(
- side_effect=AuthenticationError('auth error')
- )
-
- """Test creating a new conversation when provider authentication fails."""
- with _patch_store():
- # Mock the create_new_conversation function
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = 'test_conversation_id'
-
- # Create the request object
- test_request = InitSessionRequest(
- repository='test/repo',
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- )
-
- # Call new_conversation
- with pytest.raises(AuthenticationError):
- await create_new_test_conversation(test_request)
-
- # Verify that verify_repo_provider was called with the repository
- provider_handler_mock.verify_repo_provider.assert_called_once_with(
- 'test/repo', None
- )
-
- # Verify that create_new_conversation was not called
- mock_create_conversation.assert_not_called()
-
-
-async def test_new_conversation_with_unsupported_params():
- """Test that unsupported parameters are rejected."""
- # Create a test request with an unsupported parameter
- with _patch_store():
- # Create a direct instance of InitSessionRequest to test validation
- with pytest.raises(Exception) as excinfo:
- # This should raise a validation error because of the extra parameter
- InitSessionRequest(
- repository='test/repo',
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- unsupported_param='unsupported param', # This should cause validation to fail
- )
-
- # Verify that the error message mentions the unsupported parameter
- assert 'Extra inputs are not permitted' in str(excinfo.value)
- assert 'unsupported_param' in str(excinfo.value)
-
-
-async def test_new_conversation_with_create_microagent(provider_handler_mock):
- """Test creating a new conversation with a CreateMicroagent object."""
- with _patch_store():
- # Mock the create_new_conversation function directly
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = MagicMock(
- conversation_id='test_conversation_id',
- url='https://my-conversation.com',
- session_api_key=None,
- status=ConversationStatus.RUNNING,
- )
-
- # Create the CreateMicroagent object
- create_microagent = CreateMicroagent(
- repo='test/repo',
- git_provider=ProviderType.GITHUB,
- title='Create a new microagent',
- )
-
- test_request = InitSessionRequest(
- repository=None, # Not set in request, should be set from create_microagent
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- create_microagent=create_microagent,
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, ConversationResponse)
- assert response.status == 'ok'
- assert response.conversation_id is not None
- assert isinstance(response.conversation_id, str)
-
- # Verify that create_new_conversation was called with the correct arguments
- mock_create_conversation.assert_called_once()
- call_args = mock_create_conversation.call_args[1]
- assert call_args['user_id'] == 'test_user'
- assert (
- call_args['selected_repository'] == 'test/repo'
- ) # Should be set from create_microagent
- assert call_args['selected_branch'] == 'main'
- assert call_args['initial_user_msg'] == 'Hello, agent!'
- assert (
- call_args['conversation_trigger']
- == ConversationTrigger.MICROAGENT_MANAGEMENT
- )
- assert (
- call_args['git_provider'] == ProviderType.GITHUB
- ) # Should be set from create_microagent
-
-
-async def test_new_conversation_with_create_microagent_repository_override(
- provider_handler_mock,
-):
- """Test creating a new conversation with CreateMicroagent when repository is already set."""
- with _patch_store():
- # Mock the create_new_conversation function directly
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = MagicMock(
- conversation_id='test_conversation_id',
- url='https://my-conversation.com',
- session_api_key=None,
- status=ConversationStatus.RUNNING,
- )
-
- # Create the CreateMicroagent object
- create_microagent = CreateMicroagent(
- repo='microagent/repo',
- git_provider=ProviderType.GITLAB,
- title='Create a new microagent',
- )
-
- test_request = InitSessionRequest(
- repository='existing/repo', # Already set in request
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- create_microagent=create_microagent,
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, ConversationResponse)
- assert response.status == 'ok'
- assert response.conversation_id is not None
- assert isinstance(response.conversation_id, str)
-
- # Verify that create_new_conversation was called with the correct arguments
- mock_create_conversation.assert_called_once()
- call_args = mock_create_conversation.call_args[1]
- assert call_args['user_id'] == 'test_user'
- assert (
- call_args['selected_repository'] == 'existing/repo'
- ) # Should keep existing value
- assert call_args['selected_branch'] == 'main'
- assert call_args['initial_user_msg'] == 'Hello, agent!'
- assert (
- call_args['conversation_trigger']
- == ConversationTrigger.MICROAGENT_MANAGEMENT
- )
- assert (
- call_args['git_provider'] == ProviderType.GITLAB
- ) # Should be set from create_microagent
-
-
-async def test_new_conversation_with_create_microagent_minimal(provider_handler_mock):
- """Test creating a new conversation with minimal CreateMicroagent object (only repo field)."""
- with _patch_store():
- # Mock the create_new_conversation function directly
- with patch(
- 'openhands.server.routes.manage_conversations.create_new_conversation'
- ) as mock_create_conversation:
- # Set up the mock to return a conversation ID
- mock_create_conversation.return_value = MagicMock(
- conversation_id='test_conversation_id',
- url='https://my-conversation.com',
- session_api_key=None,
- status=ConversationStatus.RUNNING,
- )
-
- # Create the CreateMicroagent object with only required field
- create_microagent = CreateMicroagent(
- repo='minimal/repo',
- )
-
- test_request = InitSessionRequest(
- repository=None,
- selected_branch='main',
- initial_user_msg='Hello, agent!',
- create_microagent=create_microagent,
- )
-
- # Call new_conversation
- response = await create_new_test_conversation(test_request)
-
- # Verify the response
- assert isinstance(response, ConversationResponse)
- assert response.status == 'ok'
- assert response.conversation_id is not None
- assert isinstance(response.conversation_id, str)
-
- # Verify that create_new_conversation was called with the correct arguments
- mock_create_conversation.assert_called_once()
- call_args = mock_create_conversation.call_args[1]
- assert call_args['user_id'] == 'test_user'
- assert (
- call_args['selected_repository'] == 'minimal/repo'
- ) # Should be set from create_microagent
- assert call_args['selected_branch'] == 'main'
- assert call_args['initial_user_msg'] == 'Hello, agent!'
- assert (
- call_args['conversation_trigger']
- == ConversationTrigger.MICROAGENT_MANAGEMENT
- )
- assert (
- call_args['git_provider'] is None
- ) # Should remain None since not set in create_microagent
-
-
-async def test_search_conversations_with_pr_number():
- """Test searching conversations includes pr_number field in response."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_with_pr',
- title='Conversation with PR',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- pr_number=[123, 456], # Multiple PR numbers
- )
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify the result includes pr_number field
- assert len(result_set.results) == 1
- conversation_info = result_set.results[0]
- assert conversation_info.pr_number == [123, 456]
- assert conversation_info.conversation_id == 'conversation_with_pr'
- assert conversation_info.title == 'Conversation with PR'
-
-
-async def test_search_conversations_with_empty_pr_number():
- """Test searching conversations with empty pr_number field."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_no_pr',
- title='Conversation without PR',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- pr_number=[], # Empty PR numbers list
- )
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify the result includes empty pr_number field
- assert len(result_set.results) == 1
- conversation_info = result_set.results[0]
- assert conversation_info.pr_number == []
- assert conversation_info.conversation_id == 'conversation_no_pr'
- assert conversation_info.title == 'Conversation without PR'
-
-
-async def test_search_conversations_with_single_pr_number():
- """Test searching conversations with single PR number."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_single_pr',
- title='Conversation with Single PR',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- pr_number=[789], # Single PR number
- )
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify the result includes single pr_number
- assert len(result_set.results) == 1
- conversation_info = result_set.results[0]
- assert conversation_info.pr_number == [789]
- assert conversation_info.conversation_id == 'conversation_single_pr'
- assert conversation_info.title == 'Conversation with Single PR'
-
-
-async def test_get_conversation_with_pr_number():
- """Test getting a single conversation includes pr_number field."""
- with _patch_store():
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.get_metadata = AsyncMock(
- return_value=ConversationMetadata(
- conversation_id='conversation_with_pr',
- title='Conversation with PR',
- created_at=datetime.fromisoformat('2025-01-01T00:00:00+00:00'),
- last_updated_at=datetime.fromisoformat('2025-01-01T00:01:00+00:00'),
- selected_repository='test/repo',
- user_id='12345',
- pr_number=[123, 456, 789], # Multiple PR numbers
- )
- )
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.is_agent_loop_running = AsyncMock(return_value=False)
- mock_manager.get_connections = AsyncMock(return_value={})
- mock_manager.get_agent_loop_info = AsyncMock(return_value=[])
-
- conversation = await get_conversation(
- 'conversation_with_pr', conversation_store=mock_store
- )
-
- expected = ConversationInfo(
- conversation_id='conversation_with_pr',
- title='Conversation with PR',
- created_at=datetime.fromisoformat('2025-01-01T00:00:00+00:00'),
- last_updated_at=datetime.fromisoformat('2025-01-01T00:01:00+00:00'),
- status=ConversationStatus.STOPPED,
- selected_repository='test/repo',
- num_connections=0,
- url=None,
- pr_number=[123, 456, 789], # Should include PR numbers
- )
- assert conversation == expected
-
-
-async def test_search_conversations_multiple_with_pr_numbers():
- """Test searching conversations with multiple conversations having different PR numbers."""
- with _patch_store():
- with patch(
- 'openhands.server.routes.manage_conversations.config'
- ) as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(
- results=[
- ConversationMetadata(
- conversation_id='conversation_1',
- title='Conversation 1',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- pr_number=[100, 200], # Multiple PR numbers
- ),
- ConversationMetadata(
- conversation_id='conversation_2',
- title='Conversation 2',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- pr_number=[], # Empty PR numbers
- ),
- ConversationMetadata(
- conversation_id='conversation_3',
- title='Conversation 3',
- created_at=datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- ),
- last_updated_at=datetime.fromisoformat(
- '2025-01-01T00:01:00+00:00'
- ),
- selected_repository='test/repo',
- user_id='12345',
- pr_number=[300], # Single PR number
- ),
- ]
- )
- )
-
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = AppConversationPage(
- items=[]
- )
-
- result_set = await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify all results include pr_number field
- assert len(result_set.results) == 3
-
- # Check first conversation
- assert result_set.results[0].conversation_id == 'conversation_1'
- assert result_set.results[0].pr_number == [100, 200]
-
- # Check second conversation
- assert result_set.results[1].conversation_id == 'conversation_2'
- assert result_set.results[1].pr_number == []
-
- # Check third conversation
- assert result_set.results[2].conversation_id == 'conversation_3'
- assert result_set.results[2].pr_number == [300]
-
-
-async def test_delete_v1_conversation_with_sub_conversations():
- """Test V1 conversation deletion cascades to delete all sub-conversations."""
- parent_uuid = uuid4()
- str(parent_uuid)
- sub1_uuid = uuid4()
- sub2_uuid = uuid4()
-
- # Create a real service instance to test the cascade deletion logic
- mock_info_service = MagicMock(spec=SQLAppConversationInfoService)
- mock_start_task_service = MagicMock()
- mock_sandbox_service = MagicMock()
- mock_httpx_client = MagicMock()
-
- # Mock parent conversation
- parent_conversation = AppConversation(
- id=parent_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Parent Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sub-conversations
- sub1_conversation = AppConversation(
- id=sub1_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id', # Same sandbox as parent
- title='Sub Conversation 1',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key-sub1',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- sub2_conversation = AppConversation(
- id=sub2_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id', # Same sandbox as parent
- title='Sub Conversation 2',
- sandbox_status=SandboxStatus.PAUSED,
- execution_status=None,
- session_api_key=None,
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock get_app_conversation to return conversations
- async def mock_get_app_conversation(conv_id):
- if conv_id == parent_uuid:
- return parent_conversation
- elif conv_id == sub1_uuid:
- return sub1_conversation
- elif conv_id == sub2_uuid:
- return sub2_conversation
- return None
-
- # Mock get_sub_conversation_ids to return sub-conversation IDs
- mock_info_service.get_sub_conversation_ids = AsyncMock(
- return_value=[sub1_uuid, sub2_uuid]
- )
-
- # Mock delete methods
- mock_info_service.delete_app_conversation_info = AsyncMock(return_value=True)
- mock_start_task_service.delete_app_conversation_start_tasks = AsyncMock(
- return_value=True
- )
-
- # Mock sandbox service - use actual SandboxInfo model
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- # Mock httpx client for agent server calls
- mock_response = MagicMock()
- mock_response.raise_for_status = MagicMock()
- mock_httpx_client.delete = AsyncMock(return_value=mock_response)
-
- # Create service instance
- mock_user_context = MagicMock(spec=UserContext)
- mock_user_context.get_user_id = AsyncMock(return_value='test_user')
-
- service = LiveStatusAppConversationService(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
- app_conversation_info_service=mock_info_service,
- app_conversation_start_task_service=mock_start_task_service,
- event_callback_service=MagicMock(),
- event_service=MagicMock(),
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=MagicMock(),
- jwt_service=MagicMock(),
- pending_message_service=MagicMock(),
- sandbox_startup_timeout=120,
- sandbox_startup_poll_frequency=2,
- max_num_conversations_per_sandbox=20,
- httpx_client=mock_httpx_client,
- web_url=None,
- openhands_provider_base_url=None,
- access_token_hard_timeout=None,
- )
-
- # Mock get_app_conversation method
- service.get_app_conversation = mock_get_app_conversation
-
- # Execute deletion
- result = await service.delete_app_conversation(parent_uuid)
-
- # Verify result
- assert result is True
-
- # Verify get_sub_conversation_ids was called with parent ID
- mock_info_service.get_sub_conversation_ids.assert_called_once_with(parent_uuid)
-
- # Verify sub-conversations were deleted (from database)
- assert (
- mock_info_service.delete_app_conversation_info.call_count == 3
- ) # 2 subs + 1 parent
- delete_calls = [
- call_args[0][0]
- for call_args in mock_info_service.delete_app_conversation_info.call_args_list
- ]
- assert sub1_uuid in delete_calls
- assert sub2_uuid in delete_calls
- assert parent_uuid in delete_calls
-
- # Verify sub-conversation start tasks were deleted
- assert mock_start_task_service.delete_app_conversation_start_tasks.call_count == 3
- task_delete_calls = [
- call_args[0][0]
- for call_args in mock_start_task_service.delete_app_conversation_start_tasks.call_args_list
- ]
- assert sub1_uuid in task_delete_calls
- assert sub2_uuid in task_delete_calls
- assert parent_uuid in task_delete_calls
-
- # Verify agent server was called for running sub-conversations
- # sub1 has session_api_key and is running, so it should be deleted from agent server
- # sub2 is paused (no session_api_key), so no agent server call
- # parent is running, so it should be deleted from agent server
- assert mock_httpx_client.delete.call_count == 2 # sub1 + parent
- delete_urls = [
- call_args[0][0] for call_args in mock_httpx_client.delete.call_args_list
- ]
- # The URL format is: http://agent:8000/api/conversations/{uuid}
- # UUID is converted to string in the URL
- assert any(f'/api/conversations/{sub1_uuid}' in url for url in delete_urls)
- assert any(f'/api/conversations/{parent_uuid}' in url for url in delete_urls)
-
-
-async def test_delete_v1_conversation_with_no_sub_conversations():
- """Test V1 conversation deletion when there are no sub-conversations."""
- parent_uuid = uuid4()
-
- # Create a real service instance
- mock_info_service = MagicMock(spec=SQLAppConversationInfoService)
- mock_start_task_service = MagicMock()
- mock_sandbox_service = MagicMock()
- mock_httpx_client = MagicMock()
-
- # Mock parent conversation
- parent_conversation = AppConversation(
- id=parent_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Parent Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock no sub-conversations
- mock_info_service.get_sub_conversation_ids = AsyncMock(return_value=[])
- mock_info_service.delete_app_conversation_info = AsyncMock(return_value=True)
- mock_start_task_service.delete_app_conversation_start_tasks = AsyncMock(
- return_value=True
- )
-
- # Mock sandbox service - use actual SandboxInfo model
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- # Mock httpx client
- mock_response = MagicMock()
- mock_response.raise_for_status = MagicMock()
- mock_httpx_client.delete = AsyncMock(return_value=mock_response)
-
- # Create service instance
- mock_user_context = MagicMock(spec=UserContext)
- mock_user_context.get_user_id = AsyncMock(return_value='test_user')
-
- service = LiveStatusAppConversationService(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
- app_conversation_info_service=mock_info_service,
- app_conversation_start_task_service=mock_start_task_service,
- event_callback_service=MagicMock(),
- event_service=MagicMock(),
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=MagicMock(),
- jwt_service=MagicMock(),
- pending_message_service=MagicMock(),
- sandbox_startup_timeout=120,
- sandbox_startup_poll_frequency=2,
- max_num_conversations_per_sandbox=20,
- httpx_client=mock_httpx_client,
- web_url=None,
- openhands_provider_base_url=None,
- access_token_hard_timeout=None,
- )
-
- # Mock get_app_conversation method
- service.get_app_conversation = AsyncMock(return_value=parent_conversation)
-
- # Execute deletion
- result = await service.delete_app_conversation(parent_uuid)
-
- # Verify result
- assert result is True
-
- # Verify get_sub_conversation_ids was called
- mock_info_service.get_sub_conversation_ids.assert_called_once_with(parent_uuid)
-
- # Verify only parent was deleted
- mock_info_service.delete_app_conversation_info.assert_called_once_with(parent_uuid)
- mock_start_task_service.delete_app_conversation_start_tasks.assert_called_once_with(
- parent_uuid
- )
-
- # Verify agent server was called for parent
- mock_httpx_client.delete.assert_called_once()
-
-
-async def test_delete_v1_conversation_sub_conversation_deletion_error():
- """Test that deletion continues even if one sub-conversation fails to delete."""
- parent_uuid = uuid4()
- sub1_uuid = uuid4()
- sub2_uuid = uuid4()
-
- # Create a real service instance
- mock_info_service = MagicMock(spec=SQLAppConversationInfoService)
- mock_start_task_service = MagicMock()
- mock_sandbox_service = MagicMock()
- mock_httpx_client = MagicMock()
-
- # Mock parent conversation
- parent_conversation = AppConversation(
- id=parent_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Parent Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sub-conversations
- AppConversation(
- id=sub1_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Sub Conversation 1',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key-sub1',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- sub2_conversation = AppConversation(
- id=sub2_uuid,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Sub Conversation 2',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key-sub2',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock get_sub_conversation_ids
- mock_info_service.get_sub_conversation_ids = AsyncMock(
- return_value=[sub1_uuid, sub2_uuid]
- )
-
- # Mock get_app_conversation to raise error for sub1, but work for sub2
- async def mock_get_app_conversation(conv_id):
- if conv_id == parent_uuid:
- return parent_conversation
- elif conv_id == sub1_uuid:
- raise Exception('Failed to get sub-conversation 1')
- elif conv_id == sub2_uuid:
- return sub2_conversation
- return None
-
- # Mock delete methods - sub1 will fail, sub2 and parent should succeed
- def mock_delete_info(conv_id: uuid.UUID):
- if conv_id == sub1_uuid:
- raise Exception('Failed to delete sub-conversation 1')
- return True
-
- mock_info_service.delete_app_conversation_info = AsyncMock(
- side_effect=mock_delete_info
- )
- mock_start_task_service.delete_app_conversation_start_tasks = AsyncMock(
- return_value=True
- )
-
- # Mock sandbox service - use actual SandboxInfo model
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- # Mock httpx client
- mock_response = MagicMock()
- mock_response.raise_for_status = MagicMock()
- mock_httpx_client.delete = AsyncMock(return_value=mock_response)
-
- # Create service instance
- mock_user_context = MagicMock(spec=UserContext)
- mock_user_context.get_user_id = AsyncMock(return_value='test_user')
-
- service = LiveStatusAppConversationService(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
- app_conversation_info_service=mock_info_service,
- app_conversation_start_task_service=mock_start_task_service,
- event_callback_service=MagicMock(),
- event_service=MagicMock(),
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=MagicMock(),
- jwt_service=MagicMock(),
- pending_message_service=MagicMock(),
- sandbox_startup_timeout=120,
- sandbox_startup_poll_frequency=2,
- max_num_conversations_per_sandbox=20,
- httpx_client=mock_httpx_client,
- web_url=None,
- openhands_provider_base_url=None,
- access_token_hard_timeout=None,
- )
-
- # Mock get_app_conversation method
- service.get_app_conversation = mock_get_app_conversation
-
- # Execute deletion - should succeed despite sub1 failure
- result = await service.delete_app_conversation(parent_uuid)
-
- # Verify result - should still succeed
- assert result is True
-
- # Verify get_sub_conversation_ids was called
- mock_info_service.get_sub_conversation_ids.assert_called_once_with(parent_uuid)
-
- # Verify sub2 and parent were deleted (sub1 failed but didn't stop the process)
- # The delete_app_conversation_info should be called for sub2 and parent
- # (sub1 fails in get_app_conversation, so it never gets to delete)
- delete_calls = [
- call_args[0][0]
- for call_args in mock_info_service.delete_app_conversation_info.call_args_list
- ]
- assert sub2_uuid in delete_calls
- assert parent_uuid in delete_calls
- assert sub1_uuid not in delete_calls # Failed before deletion
-
-
-async def test_read_conversation_file_success():
- """Test successfully retrieving file content from conversation workspace."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
- file_content = '# Project Plan\n\n## Phase 1\n- Task 1\n- Task 2\n'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
-
- # Mock sandbox spec
- mock_sandbox_spec = SandboxSpecInfo(
- id='test-spec-id',
- command=None,
- working_dir='/workspace',
- created_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(
- return_value=mock_sandbox_spec
- )
-
- # Mock tempfile and file operations
- temp_file_path = '/tmp/test_file_12345'
- mock_file_result = FileOperationResult(
- success=True,
- source_path=file_path,
- destination_path=temp_file_path,
- file_size=len(file_content.encode('utf-8')),
- )
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.AsyncRemoteWorkspace'
- ) as mock_workspace_class:
- mock_workspace = MagicMock(spec=AsyncRemoteWorkspace)
- mock_workspace.file_download = AsyncMock(return_value=mock_file_result)
- mock_workspace_class.return_value = mock_workspace
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.tempfile.NamedTemporaryFile'
- ) as mock_tempfile:
- mock_temp_file = MagicMock()
- mock_temp_file.name = temp_file_path
- mock_tempfile.return_value.__enter__ = MagicMock(
- return_value=mock_temp_file
- )
- mock_tempfile.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch('builtins.open', create=True) as mock_open:
- mock_file_handle = MagicMock()
- mock_file_handle.read.return_value = file_content.encode('utf-8')
- mock_open.return_value.__enter__ = MagicMock(
- return_value=mock_file_handle
- )
- mock_open.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.os.unlink'
- ) as mock_unlink:
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == file_content
-
- # Verify services were called correctly
- mock_app_conversation_service.get_app_conversation.assert_called_once_with(
- conversation_id
- )
- mock_sandbox_service.get_sandbox.assert_called_once_with(
- 'test-sandbox-id'
- )
- mock_sandbox_spec_service.get_sandbox_spec.assert_called_once_with(
- 'test-spec-id'
- )
-
- # Verify workspace was created and file_download was called
- mock_workspace_class.assert_called_once()
- mock_workspace.file_download.assert_called_once_with(
- source_path=file_path,
- destination_path=temp_file_path,
- )
-
- # Verify file was read and cleaned up
- mock_open.assert_called_once_with(temp_file_path, 'rb')
- mock_unlink.assert_called_once_with(temp_file_path)
-
-
-async def test_read_conversation_file_different_path():
- """Test successfully retrieving file content from a different file path."""
- conversation_id = uuid4()
- file_path = '/workspace/project/src/main.py'
- file_content = 'def main():\n print("Hello, World!")\n'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
-
- # Mock sandbox spec
- mock_sandbox_spec = SandboxSpecInfo(
- id='test-spec-id',
- command=None,
- working_dir='/workspace',
- created_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(
- return_value=mock_sandbox_spec
- )
-
- # Mock tempfile and file operations
- temp_file_path = '/tmp/test_file_67890'
- mock_file_result = FileOperationResult(
- success=True,
- source_path=file_path,
- destination_path=temp_file_path,
- file_size=len(file_content.encode('utf-8')),
- )
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.AsyncRemoteWorkspace'
- ) as mock_workspace_class:
- mock_workspace = MagicMock(spec=AsyncRemoteWorkspace)
- mock_workspace.file_download = AsyncMock(return_value=mock_file_result)
- mock_workspace_class.return_value = mock_workspace
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.tempfile.NamedTemporaryFile'
- ) as mock_tempfile:
- mock_temp_file = MagicMock()
- mock_temp_file.name = temp_file_path
- mock_tempfile.return_value.__enter__ = MagicMock(
- return_value=mock_temp_file
- )
- mock_tempfile.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch('builtins.open', create=True) as mock_open:
- mock_file_handle = MagicMock()
- mock_file_handle.read.return_value = file_content.encode('utf-8')
- mock_open.return_value.__enter__ = MagicMock(
- return_value=mock_file_handle
- )
- mock_open.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.os.unlink'
- ) as mock_unlink:
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == file_content
-
- # Verify workspace was created and file_download was called
- mock_workspace_class.assert_called_once()
- mock_workspace.file_download.assert_called_once_with(
- source_path=file_path,
- destination_path=temp_file_path,
- )
-
- # Verify file was read and cleaned up
- mock_open.assert_called_once_with(temp_file_path, 'rb')
- mock_unlink.assert_called_once_with(temp_file_path)
-
-
-async def test_read_conversation_file_conversation_not_found():
- """Test when conversation doesn't exist."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(return_value=None)
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_spec_service = MagicMock()
-
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == ''
-
- # Verify only conversation service was called
- mock_app_conversation_service.get_app_conversation.assert_called_once_with(
- conversation_id
- )
- mock_sandbox_service.get_sandbox.assert_not_called()
- mock_sandbox_spec_service.get_sandbox_spec.assert_not_called()
-
-
-async def test_read_conversation_file_sandbox_not_found():
- """Test when sandbox doesn't exist."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=None)
-
- mock_sandbox_spec_service = MagicMock()
-
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == ''
-
- # Verify services were called
- mock_app_conversation_service.get_app_conversation.assert_called_once_with(
- conversation_id
- )
- mock_sandbox_service.get_sandbox.assert_called_once_with('test-sandbox-id')
- mock_sandbox_spec_service.get_sandbox_spec.assert_not_called()
-
-
-async def test_read_conversation_file_sandbox_not_running():
- """Test when sandbox is not in RUNNING status."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.PAUSED,
- execution_status=None,
- session_api_key=None,
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.PAUSED,
- session_api_key=None,
- exposed_urls=None,
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
-
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == ''
-
- # Verify services were called
- mock_app_conversation_service.get_app_conversation.assert_called_once_with(
- conversation_id
- )
- mock_sandbox_service.get_sandbox.assert_called_once_with('test-sandbox-id')
- mock_sandbox_spec_service.get_sandbox_spec.assert_not_called()
-
-
-async def test_read_conversation_file_sandbox_spec_not_found():
- """Test when sandbox spec doesn't exist."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(return_value=None)
-
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == ''
-
- # Verify services were called
- mock_app_conversation_service.get_app_conversation.assert_called_once_with(
- conversation_id
- )
- mock_sandbox_service.get_sandbox.assert_called_once_with('test-sandbox-id')
- mock_sandbox_spec_service.get_sandbox_spec.assert_called_once_with('test-spec-id')
-
-
-async def test_read_conversation_file_no_exposed_urls():
- """Test when sandbox has no exposed URLs."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox with no exposed URLs
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=None,
- )
-
- # Mock sandbox spec
- mock_sandbox_spec = SandboxSpecInfo(
- id='test-spec-id',
- command=None,
- working_dir='/workspace',
- created_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(
- return_value=mock_sandbox_spec
- )
-
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == ''
-
-
-async def test_read_conversation_file_no_agent_server_url():
- """Test when sandbox has exposed URLs but no AGENT_SERVER."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox with exposed URLs but no AGENT_SERVER
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name='OTHER_SERVICE', url='http://other:9000', port=9000)
- ],
- )
-
- # Mock sandbox spec
- mock_sandbox_spec = SandboxSpecInfo(
- id='test-spec-id',
- command=None,
- working_dir='/workspace',
- created_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(
- return_value=mock_sandbox_spec
- )
-
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result
- assert result == ''
-
-
-async def test_read_conversation_file_file_not_found():
- """Test when file doesn't exist."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
-
- # Mock sandbox spec
- mock_sandbox_spec = SandboxSpecInfo(
- id='test-spec-id',
- command=None,
- working_dir='/workspace',
- created_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(
- return_value=mock_sandbox_spec
- )
-
- # Mock tempfile and file operations for file not found
- temp_file_path = '/tmp/test_file_not_found'
- mock_file_result = FileOperationResult(
- success=False,
- source_path=file_path,
- destination_path=temp_file_path,
- error=f'File not found: {file_path}',
- )
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.AsyncRemoteWorkspace'
- ) as mock_workspace_class:
- mock_workspace = MagicMock(spec=AsyncRemoteWorkspace)
- mock_workspace.file_download = AsyncMock(return_value=mock_file_result)
- mock_workspace_class.return_value = mock_workspace
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.tempfile.NamedTemporaryFile'
- ) as mock_tempfile:
- mock_temp_file = MagicMock()
- mock_temp_file.name = temp_file_path
- mock_tempfile.return_value.__enter__ = MagicMock(
- return_value=mock_temp_file
- )
- mock_tempfile.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.os.unlink'
- ) as mock_unlink:
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result (empty string when file_download fails)
- assert result == ''
-
- # Verify cleanup still happens
- mock_unlink.assert_called_once_with(temp_file_path)
-
-
-async def test_read_conversation_file_empty_file():
- """Test when file exists but is empty."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
-
- # Mock sandbox spec
- mock_sandbox_spec = SandboxSpecInfo(
- id='test-spec-id',
- command=None,
- working_dir='/workspace',
- created_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(
- return_value=mock_sandbox_spec
- )
-
- # Mock tempfile and file operations for empty file
- temp_file_path = '/tmp/test_file_empty'
- empty_content = ''
- mock_file_result = FileOperationResult(
- success=True,
- source_path=file_path,
- destination_path=temp_file_path,
- file_size=0,
- )
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.AsyncRemoteWorkspace'
- ) as mock_workspace_class:
- mock_workspace = MagicMock(spec=AsyncRemoteWorkspace)
- mock_workspace.file_download = AsyncMock(return_value=mock_file_result)
- mock_workspace_class.return_value = mock_workspace
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.tempfile.NamedTemporaryFile'
- ) as mock_tempfile:
- mock_temp_file = MagicMock()
- mock_temp_file.name = temp_file_path
- mock_tempfile.return_value.__enter__ = MagicMock(
- return_value=mock_temp_file
- )
- mock_tempfile.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch('builtins.open', create=True) as mock_open:
- mock_file_handle = MagicMock()
- mock_file_handle.read.return_value = empty_content.encode('utf-8')
- mock_open.return_value.__enter__ = MagicMock(
- return_value=mock_file_handle
- )
- mock_open.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.os.unlink'
- ) as mock_unlink:
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result (empty string when file is empty)
- assert result == ''
-
- # Verify cleanup happens
- mock_unlink.assert_called_once_with(temp_file_path)
-
-
-async def test_read_conversation_file_command_exception():
- """Test when command execution raises an exception."""
- conversation_id = uuid4()
- file_path = '/workspace/project/PLAN.md'
-
- # Mock conversation
- mock_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test-sandbox-id',
- title='Test Conversation',
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- session_api_key='test-api-key',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- trigger=ConversationTrigger.GUI,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock sandbox
- mock_sandbox = SandboxInfo(
- id='test-sandbox-id',
- created_by_user_id='test_user',
- sandbox_spec_id='test-spec-id',
- status=SandboxStatus.RUNNING,
- session_api_key='test-api-key',
- exposed_urls=[
- ExposedUrl(name=AGENT_SERVER, url='http://agent:8000', port=8000)
- ],
- )
-
- # Mock sandbox spec
- mock_sandbox_spec = SandboxSpecInfo(
- id='test-spec-id',
- command=None,
- working_dir='/workspace',
- created_at=datetime.now(timezone.utc),
- )
-
- # Mock services
- mock_app_conversation_service = MagicMock()
- mock_app_conversation_service.get_app_conversation = AsyncMock(
- return_value=mock_conversation
- )
-
- mock_sandbox_service = MagicMock()
- mock_sandbox_service.get_sandbox = AsyncMock(return_value=mock_sandbox)
-
- mock_sandbox_spec_service = MagicMock()
- mock_sandbox_spec_service.get_sandbox_spec = AsyncMock(
- return_value=mock_sandbox_spec
- )
-
- # Mock tempfile and file operations for exception case
- temp_file_path = '/tmp/test_file_exception'
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.AsyncRemoteWorkspace'
- ) as mock_workspace_class:
- mock_workspace = MagicMock(spec=AsyncRemoteWorkspace)
- mock_workspace.file_download = AsyncMock(
- side_effect=Exception('Connection timeout')
- )
- mock_workspace_class.return_value = mock_workspace
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.tempfile.NamedTemporaryFile'
- ) as mock_tempfile:
- mock_temp_file = MagicMock()
- mock_temp_file.name = temp_file_path
- mock_tempfile.return_value.__enter__ = MagicMock(
- return_value=mock_temp_file
- )
- mock_tempfile.return_value.__exit__ = MagicMock(return_value=None)
-
- with patch(
- 'openhands.app_server.app_conversation.app_conversation_router.os.unlink'
- ) as mock_unlink:
- # Call the endpoint
- result = await read_conversation_file(
- conversation_id=conversation_id,
- file_path=file_path,
- app_conversation_service=mock_app_conversation_service,
- sandbox_service=mock_sandbox_service,
- sandbox_spec_service=mock_sandbox_spec_service,
- )
-
- # Verify result (empty string on exception)
- assert result == ''
-
- # Verify cleanup still happens even on exception
- mock_unlink.assert_called_once_with(temp_file_path)
diff --git a/tests/unit/server/routes/test_conversation_routes.py b/tests/unit/server/routes/test_conversation_routes.py
deleted file mode 100644
index c213c1ada3..0000000000
--- a/tests/unit/server/routes/test_conversation_routes.py
+++ /dev/null
@@ -1,1894 +0,0 @@
-import json
-from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock, patch
-from uuid import uuid4
-
-import httpx
-import pytest
-from fastapi import status
-from fastapi.responses import JSONResponse
-
-from openhands.app_server.app_conversation.app_conversation_info_service import (
- AppConversationInfoService,
-)
-from openhands.app_server.app_conversation.app_conversation_models import (
- AgentType,
- AppConversation,
- AppConversationInfo,
- AppConversationPage,
- AppConversationStartRequest,
- AppConversationStartTask,
- AppConversationStartTaskStatus,
-)
-from openhands.app_server.app_conversation.app_conversation_service import (
- AppConversationService,
-)
-from openhands.app_server.sandbox.sandbox_models import SandboxStatus
-from openhands.core.config.mcp_config import MCPConfig, StdioMCPServer
-from openhands.microagent.microagent import KnowledgeMicroagent, RepoMicroagent
-from openhands.microagent.types import MicroagentMetadata, MicroagentType
-from openhands.runtime.runtime_status import RuntimeStatus
-from openhands.sdk.conversation import ConversationExecutionStatus
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.data_models.conversation_info import ConversationStatus
-from openhands.server.data_models.conversation_info_result_set import (
- ConversationInfoResultSet,
-)
-from openhands.server.routes.conversation import (
- AddMessageRequest,
- add_message,
- get_microagents,
- get_remote_runtime_config,
-)
-from openhands.server.routes.manage_conversations import (
- _RESUME_GRACE_PERIOD,
- UpdateConversationRequest,
- _get_conversation_info,
- _to_conversation_info,
- get_conversation,
- search_conversations,
- update_conversation,
-)
-from openhands.server.session.conversation import ServerConversation
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.conversation_metadata import (
- ConversationMetadata,
- ConversationTrigger,
-)
-
-
-async def test_get_microagents():
- """Test the get_microagents function directly."""
- # Create mock microagents
- repo_microagent = RepoMicroagent(
- name='test_repo',
- content='This is a test repo microagent',
- metadata=MicroagentMetadata(
- name='test_repo',
- type=MicroagentType.REPO_KNOWLEDGE,
- inputs=[], # Empty inputs to match the expected behavior
- mcp_tools=MCPConfig(
- mcpServers={
- 'git': StdioMCPServer(command='git'),
- 'file_editor': StdioMCPServer(command='editor'),
- }
- ),
- ),
- source='test_source',
- type=MicroagentType.REPO_KNOWLEDGE,
- )
-
- knowledge_microagent = KnowledgeMicroagent(
- name='test_knowledge',
- content='This is a test knowledge microagent',
- metadata=MicroagentMetadata(
- name='test_knowledge',
- type=MicroagentType.KNOWLEDGE,
- triggers=['test', 'knowledge'],
- inputs=[], # Empty inputs to match the expected behavior
- mcp_tools=MCPConfig(
- mcpServers={
- 'search': StdioMCPServer(command='search'),
- 'fetch': StdioMCPServer(command='fetch'),
- }
- ),
- ),
- source='test_source',
- type=MicroagentType.KNOWLEDGE,
- )
-
- # Mock the agent session and memory
- mock_memory = MagicMock()
- mock_memory.repo_microagents = {'test_repo': repo_microagent}
- mock_memory.knowledge_microagents = {'test_knowledge': knowledge_microagent}
-
- mock_agent_session = MagicMock()
- mock_agent_session.memory = mock_memory
-
- # Create a mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.sid = 'test_sid'
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- # Set up the mocks
- mock_manager.get_agent_session.return_value = mock_agent_session
-
- # Call the function directly
- response = await get_microagents(conversation=mock_conversation)
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 200
-
- # Parse the JSON content
- content = json.loads(response.body)
- assert 'microagents' in content
- assert len(content['microagents']) == 2
-
- # Check repo microagent
- repo_agent = next(m for m in content['microagents'] if m['name'] == 'test_repo')
- assert repo_agent['type'] == 'repo'
- assert repo_agent['content'] == 'This is a test repo microagent'
- assert repo_agent['triggers'] == []
- assert repo_agent['inputs'] == [] # Expect empty inputs
- assert repo_agent['tools'] == ['git', 'file_editor']
-
- # Check knowledge microagent
- knowledge_agent = next(
- m for m in content['microagents'] if m['name'] == 'test_knowledge'
- )
- assert knowledge_agent['type'] == 'knowledge'
- assert knowledge_agent['content'] == 'This is a test knowledge microagent'
- assert knowledge_agent['triggers'] == ['test', 'knowledge']
- assert knowledge_agent['inputs'] == [] # Expect empty inputs
- assert knowledge_agent['tools'] == ['search', 'fetch']
-
-
-async def test_get_microagents_no_agent_session():
- """Test the get_microagents function when no agent session is found."""
- # Create a mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.sid = 'test_sid'
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- # Set up the mocks
- mock_manager.get_agent_session.return_value = None
-
- # Call the function directly
- response = await get_microagents(conversation=mock_conversation)
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 404
-
- # Parse the JSON content
- content = json.loads(response.body)
- assert 'error' in content
- assert 'Agent session not found' in content['error']
-
-
-async def test_get_microagents_exception():
- """Test the get_microagents function when an exception occurs."""
- # Create a mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.sid = 'test_sid'
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- # Set up the mocks to raise an exception
- mock_manager.get_agent_session.side_effect = Exception('Test exception')
-
- # Call the function directly
- response = await get_microagents(conversation=mock_conversation)
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 500
-
- # Parse the JSON content
- content = json.loads(response.body)
- assert 'error' in content
- assert 'Test exception' in content['error']
-
-
[email protected]_conversation
-async def test_update_conversation_success():
- """Test successful conversation update."""
- # Mock data
- conversation_id = 'test_conversation_123'
- user_id = 'test_user_456'
- original_title = 'Original Title'
- new_title = 'Updated Title'
-
- # Create mock metadata
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=user_id,
- title=original_title,
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
- mock_conversation_store.save_metadata = AsyncMock()
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Mock the conversation manager socket
- mock_sio = AsyncMock()
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify the result
- assert result is True
-
- # Verify metadata was fetched
- mock_conversation_store.get_metadata.assert_called_once_with(conversation_id)
-
- # Verify metadata was updated and saved
- mock_conversation_store.save_metadata.assert_called_once()
- saved_metadata = mock_conversation_store.save_metadata.call_args[0][0]
- assert saved_metadata.title == new_title.strip()
- assert saved_metadata.last_updated_at is not None
-
- # Verify socket emission
- mock_sio.emit.assert_called_once()
- emit_call = mock_sio.emit.call_args
- assert emit_call[0][0] == 'oh_event'
- assert emit_call[0][1]['conversation_title'] == new_title
- assert emit_call[1]['to'] == f'room:{conversation_id}'
-
-
[email protected]_conversation
-async def test_update_conversation_not_found():
- """Test conversation update when conversation doesn't exist."""
- conversation_id = 'nonexistent_conversation'
- user_id = 'test_user_456'
-
- # Create mock conversation store that raises FileNotFoundError
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(side_effect=FileNotFoundError())
-
- # Create update request
- update_request = UpdateConversationRequest(title='New Title')
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify the result is a 404 error response
- assert isinstance(result, JSONResponse)
- assert result.status_code == status.HTTP_404_NOT_FOUND
-
- # Parse the JSON content
- content = json.loads(result.body)
- assert content['status'] == 'error'
- assert content['message'] == 'Conversation not found'
- assert content['msg_id'] == 'CONVERSATION$NOT_FOUND'
-
-
[email protected]_conversation
-async def test_update_conversation_permission_denied():
- """Test conversation update when user doesn't own the conversation."""
- conversation_id = 'test_conversation_123'
- user_id = 'test_user_456'
- owner_id = 'different_user_789'
-
- # Create mock metadata owned by different user
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=owner_id,
- title='Original Title',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
-
- # Create update request
- update_request = UpdateConversationRequest(title='New Title')
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify the result is a 403 error response
- assert isinstance(result, JSONResponse)
- assert result.status_code == status.HTTP_403_FORBIDDEN
-
- # Parse the JSON content
- content = json.loads(result.body)
- assert content['status'] == 'error'
- assert (
- content['message']
- == 'Permission denied: You can only update your own conversations'
- )
- assert content['msg_id'] == 'AUTHORIZATION$PERMISSION_DENIED'
-
-
[email protected]_conversation
-async def test_update_conversation_permission_denied_no_user_id():
- """Test conversation update when user_id is None and metadata has user_id."""
- conversation_id = 'test_conversation_123'
- user_id = None
- owner_id = 'some_user_789'
-
- # Create mock metadata owned by a user
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=owner_id,
- title='Original Title',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
-
- # Create update request
- update_request = UpdateConversationRequest(title='New Title')
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify the result is successful (current logic allows this)
- assert result is True
-
-
[email protected]_conversation
-async def test_update_conversation_socket_emission_error():
- """Test conversation update when socket emission fails."""
- conversation_id = 'test_conversation_123'
- user_id = 'test_user_456'
- new_title = 'Updated Title'
-
- # Create mock metadata
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=user_id,
- title='Original Title',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
- mock_conversation_store.save_metadata = AsyncMock()
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Mock the conversation manager socket to raise an exception
- mock_sio = AsyncMock()
- mock_sio.emit.side_effect = Exception('Socket error')
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function (should still succeed despite socket error)
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify the result is still successful
- assert result is True
-
- # Verify metadata was still saved
- mock_conversation_store.save_metadata.assert_called_once()
-
-
[email protected]_conversation
-async def test_update_conversation_general_exception():
- """Test conversation update when an unexpected exception occurs."""
- conversation_id = 'test_conversation_123'
- user_id = 'test_user_456'
-
- # Create mock conversation store that raises a general exception
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(
- side_effect=Exception('Database error')
- )
-
- # Create update request
- update_request = UpdateConversationRequest(title='New Title')
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify the result is a 500 error response
- assert isinstance(result, JSONResponse)
- assert result.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
-
- # Parse the JSON content
- content = json.loads(result.body)
- assert content['status'] == 'error'
- assert 'Failed to update conversation' in content['message']
- assert content['msg_id'] == 'CONVERSATION$UPDATE_ERROR'
-
-
[email protected]_conversation
-async def test_update_conversation_title_whitespace_trimming():
- """Test that conversation title is properly trimmed of whitespace."""
- conversation_id = 'test_conversation_123'
- user_id = 'test_user_456'
- title_with_whitespace = ' Trimmed Title '
- expected_title = 'Trimmed Title'
-
- # Create mock metadata
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=user_id,
- title='Original Title',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
- mock_conversation_store.save_metadata = AsyncMock()
-
- # Create update request with whitespace
- update_request = UpdateConversationRequest(title=title_with_whitespace)
-
- # Mock the conversation manager socket
- mock_sio = AsyncMock()
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify the result
- assert result is True
-
- # Verify metadata was updated with trimmed title
- mock_conversation_store.save_metadata.assert_called_once()
- saved_metadata = mock_conversation_store.save_metadata.call_args[0][0]
- assert saved_metadata.title == expected_title
-
-
[email protected]_conversation
-async def test_update_conversation_user_owns_conversation():
- """Test successful update when user owns the conversation."""
- conversation_id = 'test_conversation_123'
- user_id = 'test_user_456'
- new_title = 'Updated Title'
-
- # Create mock metadata owned by the same user
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=user_id, # Same user
- title='Original Title',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
- mock_conversation_store.save_metadata = AsyncMock()
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Mock the conversation manager socket
- mock_sio = AsyncMock()
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify success
- assert result is True
- mock_conversation_store.save_metadata.assert_called_once()
-
-
[email protected]_conversation
-async def test_update_conversation_last_updated_at_set():
- """Test that last_updated_at is properly set when updating."""
- conversation_id = 'test_conversation_123'
- user_id = 'test_user_456'
- new_title = 'Updated Title'
-
- # Create mock metadata
- original_timestamp = datetime.now(timezone.utc)
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=user_id,
- title='Original Title',
- selected_repository=None,
- last_updated_at=original_timestamp,
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
- mock_conversation_store.save_metadata = AsyncMock()
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Mock the conversation manager socket
- mock_sio = AsyncMock()
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify success
- assert result is True
-
- # Verify last_updated_at was updated
- mock_conversation_store.save_metadata.assert_called_once()
- saved_metadata = mock_conversation_store.save_metadata.call_args[0][0]
- assert saved_metadata.last_updated_at > original_timestamp
-
-
[email protected]_conversation
-async def test_update_conversation_no_user_id_no_metadata_user_id():
- """Test successful update when both user_id and metadata.user_id are None."""
- conversation_id = 'test_conversation_123'
- user_id = None
- new_title = 'Updated Title'
-
- # Create mock metadata with no user_id
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=None,
- title='Original Title',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
- mock_conversation_store.save_metadata = AsyncMock()
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Mock the conversation manager socket
- mock_sio = AsyncMock()
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- )
-
- # Verify success (should work when both are None)
- assert result is True
- mock_conversation_store.save_metadata.assert_called_once()
-
-
[email protected]_conversation
-async def test_update_v1_conversation_success():
- """Test successful V1 conversation update."""
- # Mock data
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
- user_id = 'test_user_456'
- original_title = 'Original V1 Title'
- new_title = 'Updated V1 Title'
-
- # Create mock V1 conversation info
- mock_app_conversation_info = AppConversationInfo(
- id=conversation_uuid,
- created_by_user_id=user_id,
- sandbox_id='test_sandbox_123',
- title=original_title,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock app conversation info service
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
- mock_app_conversation_info_service.save_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
-
- # Create mock conversation store (won't be used for V1)
- mock_conversation_store = MagicMock(spec=ConversationStore)
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- app_conversation_info_service=mock_app_conversation_info_service,
- )
-
- # Verify the result
- assert result is True
-
- # Verify V1 service was called
- mock_app_conversation_info_service.get_app_conversation_info.assert_called_once_with(
- conversation_uuid
- )
- mock_app_conversation_info_service.save_app_conversation_info.assert_called_once()
-
- # Verify the conversation store was NOT called (V1 doesn't use it)
- mock_conversation_store.get_metadata.assert_not_called()
-
- # Verify the saved info has updated title
- saved_info = (
- mock_app_conversation_info_service.save_app_conversation_info.call_args[0][0]
- )
- assert saved_info.title == new_title.strip()
- assert saved_info.updated_at is not None
-
-
[email protected]_conversation
-async def test_update_v1_conversation_not_found():
- """Test V1 conversation update when conversation doesn't exist."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
- user_id = 'test_user_456'
-
- # Create mock app conversation info service that returns None
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=None
- )
-
- # Create mock conversation store that also raises FileNotFoundError
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(side_effect=FileNotFoundError())
-
- # Create update request
- update_request = UpdateConversationRequest(title='New Title')
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- app_conversation_info_service=mock_app_conversation_info_service,
- )
-
- # Verify the result is a 404 error response
- assert isinstance(result, JSONResponse)
- assert result.status_code == status.HTTP_404_NOT_FOUND
-
- # Parse the JSON content
- content = json.loads(result.body)
- assert content['status'] == 'error'
- assert content['message'] == 'Conversation not found'
- assert content['msg_id'] == 'CONVERSATION$NOT_FOUND'
-
-
[email protected]_conversation
-async def test_update_v1_conversation_permission_denied():
- """Test V1 conversation update when user doesn't own the conversation."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
- user_id = 'test_user_456'
- owner_id = 'different_user_789'
-
- # Create mock V1 conversation info owned by different user
- mock_app_conversation_info = AppConversationInfo(
- id=conversation_uuid,
- created_by_user_id=owner_id,
- sandbox_id='test_sandbox_123',
- title='Original Title',
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock app conversation info service
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
-
- # Create mock conversation store (won't be used)
- mock_conversation_store = MagicMock(spec=ConversationStore)
-
- # Create update request
- update_request = UpdateConversationRequest(title='New Title')
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- app_conversation_info_service=mock_app_conversation_info_service,
- )
-
- # Verify the result is a 403 error response
- assert isinstance(result, JSONResponse)
- assert result.status_code == status.HTTP_403_FORBIDDEN
-
- # Parse the JSON content
- content = json.loads(result.body)
- assert content['status'] == 'error'
- assert (
- content['message']
- == 'Permission denied: You can only update your own conversations'
- )
- assert content['msg_id'] == 'AUTHORIZATION$PERMISSION_DENIED'
-
- # Verify save was NOT called
- mock_app_conversation_info_service.save_app_conversation_info.assert_not_called()
-
-
[email protected]_conversation
-async def test_update_v1_conversation_save_assertion_error():
- """Test V1 conversation update when save raises AssertionError (permission check)."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
- user_id = 'test_user_456'
-
- # Create mock V1 conversation info
- mock_app_conversation_info = AppConversationInfo(
- id=conversation_uuid,
- created_by_user_id=user_id,
- sandbox_id='test_sandbox_123',
- title='Original Title',
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock app conversation info service
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
- # Simulate AssertionError on save (permission check in service)
- mock_app_conversation_info_service.save_app_conversation_info = AsyncMock(
- side_effect=AssertionError('User does not own conversation')
- )
-
- # Create mock conversation store (won't be used)
- mock_conversation_store = MagicMock(spec=ConversationStore)
-
- # Create update request
- update_request = UpdateConversationRequest(title='New Title')
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- app_conversation_info_service=mock_app_conversation_info_service,
- )
-
- # Verify the result is a 403 error response
- assert isinstance(result, JSONResponse)
- assert result.status_code == status.HTTP_403_FORBIDDEN
-
- # Parse the JSON content
- content = json.loads(result.body)
- assert content['status'] == 'error'
- assert (
- content['message']
- == 'Permission denied: You can only update your own conversations'
- )
- assert content['msg_id'] == 'AUTHORIZATION$PERMISSION_DENIED'
-
-
[email protected]_conversation
-async def test_update_v1_conversation_title_whitespace_trimming():
- """Test that V1 conversation title is properly trimmed of whitespace."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
- user_id = 'test_user_456'
- title_with_whitespace = ' Trimmed V1 Title '
- expected_title = 'Trimmed V1 Title'
-
- # Create mock V1 conversation info
- mock_app_conversation_info = AppConversationInfo(
- id=conversation_uuid,
- created_by_user_id=user_id,
- sandbox_id='test_sandbox_123',
- title='Original Title',
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock app conversation info service
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
- mock_app_conversation_info_service.save_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
-
- # Create mock conversation store (won't be used)
- mock_conversation_store = MagicMock(spec=ConversationStore)
-
- # Create update request with whitespace
- update_request = UpdateConversationRequest(title=title_with_whitespace)
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- app_conversation_info_service=mock_app_conversation_info_service,
- )
-
- # Verify the result
- assert result is True
-
- # Verify the saved info has trimmed title
- saved_info = (
- mock_app_conversation_info_service.save_app_conversation_info.call_args[0][0]
- )
- assert saved_info.title == expected_title
-
-
[email protected]_conversation
-async def test_update_v1_conversation_invalid_uuid_falls_back_to_v0():
- """Test that invalid UUID conversation_id falls back to V0 logic."""
- conversation_id = 'not_a_valid_uuid_123'
- user_id = 'test_user_456'
- new_title = 'Updated Title'
-
- # Create mock V0 metadata
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id=user_id,
- title='Original Title',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock conversation store for V0
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.get_metadata = AsyncMock(return_value=mock_metadata)
- mock_conversation_store.save_metadata = AsyncMock()
-
- # Create mock app conversation info service (won't be called)
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Mock the conversation manager socket
- mock_sio = AsyncMock()
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- app_conversation_info_service=mock_app_conversation_info_service,
- )
-
- # Verify the result is successful
- assert result is True
-
- # Verify V0 store was used, not V1 service
- mock_conversation_store.get_metadata.assert_called_once_with(conversation_id)
- mock_conversation_store.save_metadata.assert_called_once()
- mock_app_conversation_info_service.get_app_conversation_info.assert_not_called()
-
-
[email protected]_conversation
-async def test_update_v1_conversation_no_socket_emission():
- """Test that V1 conversation update does NOT emit socket.io events."""
- conversation_uuid = uuid4()
- conversation_id = str(conversation_uuid)
- user_id = 'test_user_456'
- new_title = 'Updated V1 Title'
-
- # Create mock V1 conversation info
- mock_app_conversation_info = AppConversationInfo(
- id=conversation_uuid,
- created_by_user_id=user_id,
- sandbox_id='test_sandbox_123',
- title='Original Title',
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Create mock app conversation info service
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
- mock_app_conversation_info_service.save_app_conversation_info = AsyncMock(
- return_value=mock_app_conversation_info
- )
-
- # Create mock conversation store (won't be used)
- mock_conversation_store = MagicMock(spec=ConversationStore)
-
- # Create update request
- update_request = UpdateConversationRequest(title=new_title)
-
- # Mock the conversation manager socket
- mock_sio = AsyncMock()
-
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- mock_manager.sio = mock_sio
-
- # Call the function
- result = await update_conversation(
- conversation_id=conversation_id,
- data=update_request,
- user_id=user_id,
- conversation_store=mock_conversation_store,
- app_conversation_info_service=mock_app_conversation_info_service,
- )
-
- # Verify the result is successful
- assert result is True
-
- # Verify socket.io was NOT called for V1 conversation
- mock_sio.emit.assert_not_called()
-
-
-async def test_add_message_success():
- """Test successful message addition to conversation."""
- # Create a mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.sid = 'test_conversation_123'
-
- # Create message request
- message_request = AddMessageRequest(message='Hello, this is a test message!')
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- mock_manager.send_event_to_conversation = AsyncMock()
-
- # Call the function directly
- response = await add_message(
- data=message_request, conversation=mock_conversation
- )
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 200
-
- # Parse the JSON content
- content = json.loads(response.body)
- assert content['success'] is True
-
- # Verify that send_event_to_conversation was called
- mock_manager.send_event_to_conversation.assert_called_once()
- call_args = mock_manager.send_event_to_conversation.call_args
- assert call_args[0][0] == 'test_conversation_123' # conversation ID
-
- # Verify the message data structure
- message_data = call_args[0][1]
- assert message_data['action'] == 'message'
- assert message_data['args']['content'] == 'Hello, this is a test message!'
-
-
-async def test_add_message_conversation_manager_error():
- """Test add_message when conversation manager raises an exception."""
- # Create a mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.sid = 'test_conversation_123'
-
- # Create message request
- message_request = AddMessageRequest(message='Test message')
-
- # Mock the conversation manager to raise an exception
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- mock_manager.send_event_to_conversation = AsyncMock(
- side_effect=Exception('Conversation manager error')
- )
-
- # Call the function directly
- response = await add_message(
- data=message_request, conversation=mock_conversation
- )
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 500
-
- # Parse the JSON content
- content = json.loads(response.body)
- assert content['success'] is False
- assert 'Conversation manager error' in content['error']
-
-
-async def test_add_message_empty_message():
- """Test add_message with an empty message."""
- # Create a mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.sid = 'test_conversation_123'
-
- # Create message request with empty message
- message_request = AddMessageRequest(message='')
-
- # Mock the conversation manager
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- mock_manager.send_event_to_conversation = AsyncMock()
-
- # Call the function directly
- response = await add_message(
- data=message_request, conversation=mock_conversation
- )
-
- # Verify the response
- assert isinstance(response, JSONResponse)
- assert response.status_code == 200
-
- # Parse the JSON content
- content = json.loads(response.body)
- assert content['success'] is True
-
- # Verify that send_event_to_conversation was called with empty content
- mock_manager.send_event_to_conversation.assert_called_once()
- call_args = mock_manager.send_event_to_conversation.call_args
- message_data = call_args[0][1]
- assert message_data['args']['content'] == ''
-
-
[email protected]_conversation
-async def test_create_sub_conversation_with_planning_agent():
- """Test creating a sub-conversation from a parent conversation with planning agent."""
- parent_conversation_id = uuid4()
- user_id = 'test_user_456'
- sandbox_id = 'test_sandbox_123'
-
- # Create mock parent conversation info
- parent_info = AppConversationInfo(
- id=parent_conversation_id,
- created_by_user_id=user_id,
- sandbox_id=sandbox_id,
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=None,
- title='Parent Conversation',
- llm_model='anthropic/claude-3-5-sonnet-20241022',
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Create sub-conversation request with planning agent
- sub_conversation_request = AppConversationStartRequest(
- parent_conversation_id=parent_conversation_id,
- agent_type=AgentType.PLAN,
- initial_message=None,
- )
-
- # Create mock app conversation service
- mock_app_conversation_service = MagicMock(spec=AppConversationService)
- mock_app_conversation_info_service = MagicMock(spec=AppConversationInfoService)
-
- # Mock the service to return parent info
- mock_app_conversation_info_service.get_app_conversation_info = AsyncMock(
- return_value=parent_info
- )
-
- # Mock the start_app_conversation method to return a task
- async def mock_start_generator(request):
- task = AppConversationStartTask(
- id=uuid4(),
- created_by_user_id=user_id,
- status=AppConversationStartTaskStatus.READY,
- app_conversation_id=uuid4(),
- sandbox_id=sandbox_id,
- agent_server_url='http://agent-server:8000',
- request=request,
- )
- yield task
-
- mock_app_conversation_service.start_app_conversation = mock_start_generator
-
- # Test the service method directly
- async for task in mock_app_conversation_service.start_app_conversation(
- sub_conversation_request
- ):
- # Verify the task was created with planning agent
- assert task is not None
- assert task.status == AppConversationStartTaskStatus.READY
- assert task.request.agent_type == AgentType.PLAN
- assert task.request.parent_conversation_id == parent_conversation_id
- assert task.sandbox_id == sandbox_id
- break
-
-
-async def test_search_conversations_include_sub_conversations_default_false():
- """Test that include_sub_conversations defaults to False when not provided."""
- with patch('openhands.server.routes.manage_conversations.config') as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(results=[])
- )
-
- # Create a mock app conversation service
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = (
- AppConversationPage(items=[])
- )
-
- # Call search_conversations without include_sub_conversations parameter
- await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search_app_conversations was called with include_sub_conversations=False (default)
- mock_app_conversation_service.search_app_conversations.assert_called_once()
- call_kwargs = (
- mock_app_conversation_service.search_app_conversations.call_args[1]
- )
- assert call_kwargs.get('include_sub_conversations') is False
-
-
-async def test_search_conversations_include_sub_conversations_explicit_false():
- """Test that include_sub_conversations=False is properly passed through."""
- with patch('openhands.server.routes.manage_conversations.config') as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(results=[])
- )
-
- # Create a mock app conversation service
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = (
- AppConversationPage(items=[])
- )
-
- # Call search_conversations with include_sub_conversations=False
- await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- include_sub_conversations=False,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search_app_conversations was called with include_sub_conversations=False
- mock_app_conversation_service.search_app_conversations.assert_called_once()
- call_kwargs = (
- mock_app_conversation_service.search_app_conversations.call_args[1]
- )
- assert call_kwargs.get('include_sub_conversations') is False
-
-
-async def test_search_conversations_include_sub_conversations_explicit_true():
- """Test that include_sub_conversations=True is properly passed through."""
- with patch('openhands.server.routes.manage_conversations.config') as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(results=[])
- )
-
- # Create a mock app conversation service
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = (
- AppConversationPage(items=[])
- )
-
- # Call search_conversations with include_sub_conversations=True
- await search_conversations(
- page_id=None,
- limit=20,
- selected_repository=None,
- conversation_trigger=None,
- include_sub_conversations=True,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search_app_conversations was called with include_sub_conversations=True
- mock_app_conversation_service.search_app_conversations.assert_called_once()
- call_kwargs = (
- mock_app_conversation_service.search_app_conversations.call_args[1]
- )
- assert call_kwargs.get('include_sub_conversations') is True
-
-
-async def test_search_conversations_include_sub_conversations_with_other_filters():
- """Test that include_sub_conversations works correctly with other filters."""
- with patch('openhands.server.routes.manage_conversations.config') as mock_config:
- mock_config.conversation_max_age_seconds = 864000 # 10 days
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
-
- async def mock_get_running_agent_loops(*args, **kwargs):
- return set()
-
- async def mock_get_connections(*args, **kwargs):
- return {}
-
- async def get_agent_loop_info(*args, **kwargs):
- return []
-
- mock_manager.get_running_agent_loops = mock_get_running_agent_loops
- mock_manager.get_connections = mock_get_connections
- mock_manager.get_agent_loop_info = get_agent_loop_info
- with patch(
- 'openhands.server.routes.manage_conversations.datetime'
- ) as mock_datetime:
- mock_datetime.now.return_value = datetime.fromisoformat(
- '2025-01-01T00:00:00+00:00'
- )
- mock_datetime.fromisoformat = datetime.fromisoformat
- mock_datetime.timezone = timezone
-
- # Mock the conversation store
- mock_store = MagicMock()
- mock_store.search = AsyncMock(
- return_value=ConversationInfoResultSet(results=[])
- )
-
- # Create a mock app conversation service
- mock_app_conversation_service = AsyncMock()
- mock_app_conversation_service.search_app_conversations.return_value = (
- AppConversationPage(items=[])
- )
-
- # Create a valid base64-encoded page_id for testing
- import base64
-
- page_id_data = json.dumps({'v0': None, 'v1': 'test_v1_page_id'})
- encoded_page_id = base64.b64encode(page_id_data.encode()).decode()
-
- # Call search_conversations with include_sub_conversations and other filters
- await search_conversations(
- page_id=encoded_page_id,
- limit=50,
- selected_repository='test/repo',
- conversation_trigger=ConversationTrigger.GUI,
- include_sub_conversations=True,
- conversation_store=mock_store,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify that search_app_conversations was called with all parameters including include_sub_conversations=True
- mock_app_conversation_service.search_app_conversations.assert_called_once()
- call_kwargs = (
- mock_app_conversation_service.search_app_conversations.call_args[1]
- )
- assert call_kwargs.get('include_sub_conversations') is True
- assert call_kwargs.get('page_id') == 'test_v1_page_id'
- assert call_kwargs.get('limit') == 50
-
-
- 'sandbox_status,execution_status,server_uptime,server_error,expected_status,should_call_server',
- [
- # RUNNING sandbox, no execution_status, server responds within grace period -> STARTING
- (SandboxStatus.RUNNING, None, 30, None, ConversationStatus.STARTING, True),
- # RUNNING sandbox, no execution_status, server responds past grace period -> RUNNING
- (
- SandboxStatus.RUNNING,
- None,
- _RESUME_GRACE_PERIOD + 10,
- None,
- ConversationStatus.RUNNING,
- True,
- ),
- # RUNNING sandbox, no execution_status, server unresponsive -> STARTING
- (
- SandboxStatus.RUNNING,
- None,
- None,
- httpx.ConnectError('Connection refused'),
- ConversationStatus.STARTING,
- True,
- ),
- # RUNNING sandbox, WITH execution_status -> RUNNING, skip server check
- (SandboxStatus.RUNNING, 'IDLE', None, None, ConversationStatus.RUNNING, False),
- # Non-RUNNING sandbox -> STARTING, skip server check
- (SandboxStatus.STARTING, None, None, None, ConversationStatus.STARTING, False),
- ],
- ids=[
- 'running_no_exec_status_within_grace_period',
- 'running_no_exec_status_past_grace_period',
- 'running_no_exec_status_server_unresponsive',
- 'running_with_exec_status_skips_check',
- 'non_running_skips_check',
- ],
-)
-async def test_get_conversation_resume_status_handling(
- sandbox_status,
- execution_status,
- server_uptime,
- server_error,
- expected_status,
- should_call_server,
-):
- """Test get_conversation handles resume status correctly for various scenarios."""
- conversation_id = uuid4()
-
- # Convert string execution_status to enum if provided
- exec_status = None
- if execution_status == 'IDLE':
- exec_status = ConversationExecutionStatus.IDLE
-
- mock_app_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id='test_sandbox',
- sandbox_status=sandbox_status,
- execution_status=exec_status,
- conversation_url='https://sandbox.example.com/conversation',
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- mock_app_conversation_service = AsyncMock(spec=AppConversationService)
- mock_app_conversation_service.get_app_conversation.return_value = (
- mock_app_conversation
- )
- mock_conversation_store = AsyncMock(spec=ConversationStore)
- mock_httpx_client = AsyncMock(spec=httpx.AsyncClient)
-
- if server_error:
- mock_httpx_client.get.side_effect = server_error
- elif server_uptime is not None:
- mock_response = MagicMock()
- mock_response.json.return_value = {'uptime': server_uptime}
- mock_response.raise_for_status = MagicMock()
- mock_httpx_client.get.return_value = mock_response
-
- result = await get_conversation(
- conversation_id=str(conversation_id),
- conversation_store=mock_conversation_store,
- app_conversation_service=mock_app_conversation_service,
- httpx_client=mock_httpx_client,
- )
-
- assert result is not None
- assert result.status == expected_status
-
- if should_call_server:
- mock_httpx_client.get.assert_called_once_with(
- 'https://sandbox.example.com/server_info'
- )
- else:
- mock_httpx_client.get.assert_not_called()
-
-
-# Tests for _to_conversation_info and _get_conversation_info sandbox_id mapping
-
-
-async def test_to_conversation_info_maps_sandbox_id():
- """Test that _to_conversation_info correctly maps sandbox_id from V1 AppConversation."""
- conversation_id = uuid4()
- test_sandbox_id = 'test-sandbox-123'
-
- # Create a mock V1 AppConversation with sandbox_id
- mock_app_conversation = AppConversation(
- id=conversation_id,
- created_by_user_id='test_user',
- sandbox_id=test_sandbox_id,
- sandbox_status=SandboxStatus.RUNNING,
- execution_status=ConversationExecutionStatus.RUNNING,
- conversation_url='https://sandbox.example.com/conversation',
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- title='Test Conversation',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider='github',
- trigger=ConversationTrigger.GUI,
- sub_conversation_ids=[],
- public=False,
- )
-
- result = _to_conversation_info(mock_app_conversation)
-
- assert result is not None
- assert result.conversation_id == conversation_id.hex
- assert result.sandbox_id == test_sandbox_id
- assert result.conversation_version == 'V1'
-
-
-async def test_get_conversation_info_v0_has_null_sandbox_id():
- """Test that _get_conversation_info returns null sandbox_id for V0 conversations."""
- conversation_id = 'test-conversation-v0'
-
- # Create mock V0 conversation metadata (no sandbox_id field)
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id='test_user',
- title='V0 Test Conversation',
- selected_repository=None,
- last_updated_at=datetime.now(timezone.utc),
- created_at=datetime.now(timezone.utc),
- )
-
- # Create mock agent_loop_info
- mock_agent_loop_info = AgentLoopInfo(
- conversation_id=conversation_id,
- runtime_status=RuntimeStatus.READY,
- status=ConversationStatus.STOPPED,
- event_store=None,
- url=None,
- session_api_key=None,
- )
-
- result = await _get_conversation_info(
- conversation=mock_metadata,
- num_connections=0,
- agent_loop_info=mock_agent_loop_info,
- )
-
- assert result is not None
- assert result.sandbox_id is None
- assert result.conversation_version == 'V0'
-
-
-async def test_get_conversation_info_returns_all_fields():
- """Test that _get_conversation_info returns all expected fields for V0 conversations."""
- conversation_id = 'test-conversation-full'
-
- # Create mock V0 conversation metadata
- mock_metadata = ConversationMetadata(
- conversation_id=conversation_id,
- user_id='test_user',
- title='Full Test Conversation',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider='github',
- trigger=ConversationTrigger.GUI,
- last_updated_at=datetime.now(timezone.utc),
- created_at=datetime.now(timezone.utc),
- pr_number=[123],
- )
-
- # Create mock agent_loop_info
- mock_agent_loop_info = AgentLoopInfo(
- conversation_id=conversation_id,
- runtime_status=RuntimeStatus.READY,
- status=ConversationStatus.STOPPED,
- event_store=None,
- url='https://example.com/conversation',
- session_api_key='test-key',
- )
-
- result = await _get_conversation_info(
- conversation=mock_metadata,
- num_connections=5,
- agent_loop_info=mock_agent_loop_info,
- )
-
- assert result is not None
- assert result.conversation_id == conversation_id
- assert result.title == 'Full Test Conversation'
- assert result.selected_repository == 'test/repo'
- assert result.selected_branch == 'main'
- assert result.git_provider == 'github'
- assert result.trigger == ConversationTrigger.GUI
- assert result.num_connections == 5
- assert result.url == 'https://example.com/conversation'
- assert result.session_api_key == 'test-key'
- assert result.pr_number == [123]
- assert result.sandbox_id is None # V0 should have null sandbox_id
- assert result.conversation_version == 'V0'
-
-
-# Tests for get_remote_runtime_config endpoint (/config)
-
-
-async def test_get_remote_runtime_config_v1_conversation():
- """Test get_remote_runtime_config returns correct config for V1 conversations."""
- from uuid import UUID
-
- conversation_id = str(uuid4())
- test_sandbox_id = 'test-sandbox-v1-123'
-
- # Create mock AppConversationInfo
- mock_info = AppConversationInfo(
- id=UUID(conversation_id),
- created_by_user_id='test_user',
- sandbox_id=test_sandbox_id,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- )
-
- # Mock the AppConversationInfoService - use AsyncMock for the method
- mock_info_service = AsyncMock(spec=AppConversationInfoService)
- mock_info_service.get_app_conversation_info = AsyncMock(return_value=mock_info)
-
- # Call the function directly
- result = await get_remote_runtime_config(
- conversation_id=conversation_id,
- app_conversation_info_service=mock_info_service,
- )
-
- # Verify the response - V1 returns a JSONResponse
- assert isinstance(result, JSONResponse)
- content = json.loads(result.body)
- assert isinstance(content, dict)
- assert content['runtime_id'] == test_sandbox_id
- assert content['session_id'] == conversation_id
-
- # Verify the service was called with correct UUID
- mock_info_service.get_app_conversation_info.assert_called_once_with(
- UUID(conversation_id)
- )
-
-
-async def test_get_remote_runtime_config_v0_conversation():
- """Test get_remote_runtime_config returns correct config for V0 conversations."""
- from openhands.runtime.base import Runtime
- from openhands.server.session.conversation import ServerConversation
-
- conversation_id = 'test-conversation-v0'
- test_runtime_id = 'test-runtime-456'
- test_session_id = 'test-sid-789'
-
- # Create mock Runtime with runtime_id and sid
- mock_runtime = MagicMock(spec=Runtime)
- mock_runtime.runtime_id = test_runtime_id
- mock_runtime.sid = test_session_id
-
- # Create mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.runtime = mock_runtime
-
- # Mock the conversation_manager - use AsyncMock for attach_to_conversation
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- mock_manager.attach_to_conversation = AsyncMock(return_value=mock_conversation)
- mock_manager.detach_from_conversation = AsyncMock()
-
- # Mock the AppConversationInfoService to return None (not V1)
- mock_info_service = AsyncMock(spec=AppConversationInfoService)
- mock_info_service.get_app_conversation_info = AsyncMock(return_value=None)
-
- # Call the function directly
- result = await get_remote_runtime_config(
- conversation_id=conversation_id,
- app_conversation_info_service=mock_info_service,
- )
-
- # Verify the response
- assert isinstance(result, JSONResponse)
- assert result.status_code == 200
- content = json.loads(result.body)
- assert content['runtime_id'] == test_runtime_id
- assert content['session_id'] == test_session_id
-
-
-async def test_get_remote_runtime_config_v1_not_found_falls_back_to_v0():
- """Test get_remote_runtime_config falls back to V0 when V1 conversation not found."""
- from openhands.runtime.base import Runtime
- from openhands.server.session.conversation import ServerConversation
-
- conversation_id = 'test-conversation-v0'
- test_runtime_id = 'test-runtime-abc'
- test_session_id = 'test-sid-xyz'
-
- # Create mock Runtime
- mock_runtime = MagicMock(spec=Runtime)
- mock_runtime.runtime_id = test_runtime_id
- mock_runtime.sid = test_session_id
-
- # Create mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.runtime = mock_runtime
-
- # Mock the conversation_manager - use AsyncMock
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- mock_manager.attach_to_conversation = AsyncMock(return_value=mock_conversation)
- mock_manager.detach_from_conversation = AsyncMock()
-
- # Mock the AppConversationInfoService to return None (not found)
- mock_info_service = AsyncMock(spec=AppConversationInfoService)
- mock_info_service.get_app_conversation_info = AsyncMock(return_value=None)
-
- # Call the function directly
- result = await get_remote_runtime_config(
- conversation_id=conversation_id,
- app_conversation_info_service=mock_info_service,
- )
-
- # Verify the response - should fall back to V0 config
- assert isinstance(result, JSONResponse)
- assert result.status_code == 200
- content = json.loads(result.body)
- assert content['runtime_id'] == test_runtime_id
- assert content['session_id'] == test_session_id
-
-
-async def test_get_remote_runtime_config_invalid_uuid_falls_back_to_v0():
- """Test get_remote_runtime_config falls back to V0 for invalid UUID."""
- from openhands.runtime.base import Runtime
- from openhands.server.session.conversation import ServerConversation
-
- conversation_id = 'not-a-valid-uuid'
- test_runtime_id = 'test-runtime-def'
- test_session_id = 'test-sid-ghi'
-
- # Create mock Runtime
- mock_runtime = MagicMock(spec=Runtime)
- mock_runtime.runtime_id = test_runtime_id
- mock_runtime.sid = test_session_id
-
- # Create mock ServerConversation
- mock_conversation = MagicMock(spec=ServerConversation)
- mock_conversation.runtime = mock_runtime
-
- # Mock the conversation_manager - use AsyncMock
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- mock_manager.attach_to_conversation = AsyncMock(return_value=mock_conversation)
- mock_manager.detach_from_conversation = AsyncMock()
-
- # Mock the AppConversationInfoService - use AsyncMock for the method
- mock_info_service = AsyncMock(spec=AppConversationInfoService)
- mock_info_service.get_app_conversation_info = AsyncMock(
- side_effect=ValueError('Invalid UUID')
- )
-
- # Call the function directly
- result = await get_remote_runtime_config(
- conversation_id=conversation_id,
- app_conversation_info_service=mock_info_service,
- )
-
- # Verify the response - should fall back to V0 config
- assert isinstance(result, JSONResponse)
- assert result.status_code == 200
- content = json.loads(result.body)
- assert content['runtime_id'] == test_runtime_id
- assert content['session_id'] == test_session_id
-
-
-async def test_get_remote_runtime_config_v0_not_found():
- """Test get_remote_runtime_config returns 404 when V0 conversation not found."""
- from fastapi import HTTPException
-
- conversation_id = 'test-conversation-v0'
-
- # Mock the conversation_manager - use AsyncMock
- with patch(
- 'openhands.server.routes.conversation.conversation_manager'
- ) as mock_manager:
- mock_manager.attach_to_conversation = AsyncMock(return_value=None)
-
- # Mock the AppConversationInfoService to return None (not V1)
- mock_info_service = AsyncMock(spec=AppConversationInfoService)
- mock_info_service.get_app_conversation_info = AsyncMock(return_value=None)
-
- # Call the function and expect HTTPException
- with pytest.raises(HTTPException) as exc_info:
- await get_remote_runtime_config(
- conversation_id=conversation_id,
- app_conversation_info_service=mock_info_service,
- )
-
- assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
- assert f'Conversation {conversation_id} not found' in str(exc_info.value.detail)
diff --git a/tests/unit/server/routes/test_get_microagent_management_conversations.py b/tests/unit/server/routes/test_get_microagent_management_conversations.py
deleted file mode 100644
index 775d1e80bf..0000000000
--- a/tests/unit/server/routes/test_get_microagent_management_conversations.py
+++ /dev/null
@@ -1,754 +0,0 @@
-import base64
-import json
-from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-
-from openhands.app_server.app_conversation.app_conversation_service import (
- AppConversationService,
-)
-from openhands.integrations.provider import ProviderHandler
-from openhands.server.data_models.conversation_info_result_set import (
- ConversationInfoResultSet,
-)
-from openhands.server.routes.manage_conversations import (
- get_microagent_management_conversations,
-)
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.conversation_metadata import (
- ConversationMetadata,
- ConversationTrigger,
-)
-
-
-def _create_mock_app_conversation_service():
- """Create a mock AppConversationService that returns empty V1 results."""
- mock_service = MagicMock(spec=AppConversationService)
- mock_service.search_app_conversations = AsyncMock(
- return_value=MagicMock(items=[], next_page_id=None)
- )
- return mock_service
-
-
-def _decode_combined_page_id(page_id: str | None) -> dict:
- """Decode a combined page_id to get v0 and v1 components."""
- if not page_id:
- return {'v0': None, 'v1': None}
- try:
- return json.loads(base64.b64decode(page_id))
- except Exception:
- # Legacy format - just v0
- return {'v0': page_id, 'v1': None}
-
-
-async def _mock_wait_all(coros):
- """Mock implementation of wait_all that properly awaits coroutines."""
- results = []
- for coro in coros:
- if hasattr(coro, '__await__'):
- results.append(await coro)
- else:
- results.append(coro)
- return results
-
-
-def _setup_common_mocks():
- """Set up common mocks used by all tests."""
- return {
- 'config': patch('openhands.server.routes.manage_conversations.config'),
- 'conversation_manager': patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ),
- 'wait_all': patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- 'provider_handler': patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler'
- ),
- }
-
-
-async def test_get_microagent_management_conversations_success():
- """Test successful retrieval of microagent management conversations."""
- # Mock data
- page_id = 'test_page_123'
- limit = 10
- selected_repository = 'owner/repo'
-
- # Create mock conversations
- mock_conversations = [
- ConversationMetadata(
- conversation_id='conv_1',
- user_id='user_1',
- title='Test Conversation 1',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['123'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ConversationMetadata(
- conversation_id='conv_2',
- user_id='user_2',
- title='Test Conversation 2',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['456'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ]
-
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=mock_conversations, next_page_id='next_page_456')
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- # Mock provider handler
- mock_provider_handler = MagicMock(spec=ProviderHandler)
- mock_provider_handler.is_pr_open = AsyncMock(return_value=True)
-
- # Mock app conversation service
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler',
- return_value=mock_provider_handler,
- ),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400 # 24 hours
-
- # Mock conversation manager
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function with correct parameter order
- result = await get_microagent_management_conversations(
- selected_repository=selected_repository,
- page_id=page_id,
- limit=limit,
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify the result
- assert isinstance(result, ConversationInfoResultSet)
-
- # Decode the combined page_id to verify v0 component
- decoded_page_id = _decode_combined_page_id(result.next_page_id)
- assert decoded_page_id['v0'] == 'next_page_456'
- assert decoded_page_id['v1'] is None
-
- # Verify conversation store was called correctly
- mock_conversation_store.search.assert_called_once_with(page_id, limit)
-
- # Verify provider handler was created with correct tokens
- mock_provider_handler.is_pr_open.assert_called()
-
-
-async def test_get_microagent_management_conversations_no_results():
- """Test when no conversations match the criteria."""
- # Mock conversation store with empty results
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=[], next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch('openhands.server.routes.manage_conversations.ProviderHandler'),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function with required selected_repository parameter
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify the result
- assert isinstance(result, ConversationInfoResultSet)
- assert result.next_page_id is None
- assert len(result.results) == 0
-
-
-async def test_get_microagent_management_conversations_filter_by_repository():
- """Test filtering conversations by selected repository."""
- # Create mock conversations with different repositories
- mock_conversations = [
- ConversationMetadata(
- conversation_id='conv_1',
- user_id='user_1',
- title='Test Conversation 1',
- selected_repository='owner/repo1',
- git_provider='github',
- pr_number=['123'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ConversationMetadata(
- conversation_id='conv_2',
- user_id='user_2',
- title='Test Conversation 2',
- selected_repository='owner/repo2',
- git_provider='github',
- pr_number=['456'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ]
-
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=mock_conversations, next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- # Mock provider handler
- mock_provider_handler = MagicMock(spec=ProviderHandler)
- mock_provider_handler.is_pr_open = AsyncMock(return_value=True)
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler',
- return_value=mock_provider_handler,
- ),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function with repository filter
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo1',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify only conversations from the specified repository are returned
- assert len(result.results) == 1
- assert result.results[0].conversation_id == 'conv_1'
- assert result.results[0].selected_repository == 'owner/repo1'
-
-
-async def test_get_microagent_management_conversations_filter_by_trigger():
- """Test that only microagent_management conversations are returned."""
- # Create mock conversations with different triggers
- mock_conversations = [
- ConversationMetadata(
- conversation_id='conv_1',
- user_id='user_1',
- title='Test Conversation 1',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['123'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ConversationMetadata(
- conversation_id='conv_2',
- user_id='user_2',
- title='Test Conversation 2',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['456'],
- trigger=ConversationTrigger.GUI, # Different trigger
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ]
-
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=mock_conversations, next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- # Mock provider handler
- mock_provider_handler = MagicMock(spec=ProviderHandler)
- mock_provider_handler.is_pr_open = AsyncMock(return_value=True)
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler',
- return_value=mock_provider_handler,
- ),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify only microagent_management conversations are returned
- assert len(result.results) == 1
- assert result.results[0].conversation_id == 'conv_1'
- assert result.results[0].trigger == ConversationTrigger.MICROAGENT_MANAGEMENT
-
-
-async def test_get_microagent_management_conversations_filter_inactive_pr():
- """Test filtering out conversations with inactive PRs."""
- # Create mock conversations
- mock_conversations = [
- ConversationMetadata(
- conversation_id='conv_1',
- user_id='user_1',
- title='Test Conversation 1',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['123'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ConversationMetadata(
- conversation_id='conv_2',
- user_id='user_2',
- title='Test Conversation 2',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['456'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ]
-
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=mock_conversations, next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- # Mock provider handler with one active and one inactive PR
- mock_provider_handler = MagicMock(spec=ProviderHandler)
- mock_provider_handler.is_pr_open = AsyncMock(side_effect=[True, False])
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler',
- return_value=mock_provider_handler,
- ),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify only conversations with active PRs are returned
- assert len(result.results) == 1
- assert result.results[0].conversation_id == 'conv_1'
-
- # Verify provider handler was called for both PRs
- assert mock_provider_handler.is_pr_open.call_count == 2
-
-
-async def test_get_microagent_management_conversations_no_pr_number():
- """Test conversations without PR numbers are included."""
- # Create mock conversations without PR numbers
- mock_conversations = [
- ConversationMetadata(
- conversation_id='conv_1',
- user_id='user_1',
- title='Test Conversation 1',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=[], # No PR number
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ]
-
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=mock_conversations, next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- # Mock provider handler
- mock_provider_handler = MagicMock(spec=ProviderHandler)
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler',
- return_value=mock_provider_handler,
- ),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify conversation without PR number is included
- assert len(result.results) == 1
- assert result.results[0].conversation_id == 'conv_1'
-
- # Verify provider handler was not called (no PR to check)
- mock_provider_handler.is_pr_open.assert_not_called()
-
-
-async def test_get_microagent_management_conversations_no_repository():
- """Test conversations without selected repository are filtered out for PR checks."""
- # Create mock conversations without repository
- mock_conversations = [
- ConversationMetadata(
- conversation_id='conv_1',
- user_id='user_1',
- title='Test Conversation 1',
- selected_repository=None, # No repository
- git_provider='github',
- pr_number=['123'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=datetime.now(timezone.utc),
- last_updated_at=datetime.now(timezone.utc),
- ),
- ]
-
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=mock_conversations, next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- # Mock provider handler
- mock_provider_handler = MagicMock(spec=ProviderHandler)
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler',
- return_value=mock_provider_handler,
- ),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify conversation without repository is filtered out
- assert len(result.results) == 0
-
- # Verify provider handler was not called (no repository for PR check)
- mock_provider_handler.is_pr_open.assert_not_called()
-
-
-async def test_get_microagent_management_conversations_age_filter():
- """Test that conversations are filtered by age."""
- # Create mock conversations with different ages
- now = datetime.now(timezone.utc)
- old_conversation = ConversationMetadata(
- conversation_id='conv_old',
- user_id='user_1',
- title='Old Conversation',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['123'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=now.replace(year=now.year - 1), # Very old
- last_updated_at=now.replace(year=now.year - 1),
- )
-
- recent_conversation = ConversationMetadata(
- conversation_id='conv_recent',
- user_id='user_2',
- title='Recent Conversation',
- selected_repository='owner/repo',
- git_provider='github',
- pr_number=['456'],
- trigger=ConversationTrigger.MICROAGENT_MANAGEMENT,
- created_at=now, # Recent
- last_updated_at=now,
- )
-
- mock_conversations = [old_conversation, recent_conversation]
-
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=mock_conversations, next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- # Mock provider handler
- mock_provider_handler = MagicMock(spec=ProviderHandler)
- mock_provider_handler.is_pr_open = AsyncMock(return_value=True)
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch(
- 'openhands.server.routes.manage_conversations.ProviderHandler',
- return_value=mock_provider_handler,
- ),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config with short max age
- mock_config.conversation_max_age_seconds = 3600 # 1 hour
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify only recent conversation is returned
- assert len(result.results) == 1
- assert result.results[0].conversation_id == 'conv_recent'
-
-
-async def test_get_microagent_management_conversations_pagination():
- """Test pagination functionality."""
- # Mock conversation store with pagination
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=[], next_page_id='next_page_789')
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch('openhands.server.routes.manage_conversations.ProviderHandler'),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function with pagination parameters
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- page_id='test_page',
- limit=5,
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify pagination parameters were passed correctly
- mock_conversation_store.search.assert_called_once_with('test_page', 5)
-
- # Decode and verify the next_page_id
- decoded_page_id = _decode_combined_page_id(result.next_page_id)
- assert decoded_page_id['v0'] == 'next_page_789'
-
-
-async def test_get_microagent_management_conversations_default_parameters():
- """Test default parameter values."""
- # Mock conversation store
- mock_conversation_store = MagicMock(spec=ConversationStore)
- mock_conversation_store.search = AsyncMock(
- return_value=MagicMock(results=[], next_page_id=None)
- )
-
- # Mock provider tokens
- mock_provider_tokens = {'github': 'token_123'}
-
- mock_app_conversation_service = _create_mock_app_conversation_service()
-
- with (
- patch('openhands.server.routes.manage_conversations.ProviderHandler'),
- patch('openhands.server.routes.manage_conversations.config') as mock_config,
- patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_conv_mgr,
- patch(
- 'openhands.server.routes.manage_conversations.wait_all',
- side_effect=_mock_wait_all,
- ),
- ):
- # Mock config
- mock_config.conversation_max_age_seconds = 86400
-
- mock_conv_mgr.get_connections = AsyncMock(return_value=[])
- mock_conv_mgr.get_agent_loop_info = AsyncMock(return_value=[])
-
- # Call the function without parameters (selected_repository is required)
- result = await get_microagent_management_conversations(
- selected_repository='owner/repo',
- conversation_store=mock_conversation_store,
- provider_tokens=mock_provider_tokens,
- app_conversation_service=mock_app_conversation_service,
- )
-
- # Verify default values were used
- mock_conversation_store.search.assert_called_once_with(None, 20)
- assert isinstance(result, ConversationInfoResultSet)
diff --git a/tests/unit/server/routes/test_get_repository_microagents.py b/tests/unit/server/routes/test_get_repository_microagents.py
deleted file mode 100644
index 98084f2fef..0000000000
--- a/tests/unit/server/routes/test_get_repository_microagents.py
+++ /dev/null
@@ -1,578 +0,0 @@
-from types import MappingProxyType
-from unittest.mock import AsyncMock, patch
-from urllib.parse import quote
-
-import pytest
-from fastapi import FastAPI
-from fastapi.responses import JSONResponse
-from fastapi.testclient import TestClient
-from httpcore import Request
-from pydantic import SecretStr
-
-from openhands.app_server.utils.dependencies import check_session_api_key
-from openhands.integrations.provider import ProviderToken, ProviderType
-from openhands.integrations.service_types import (
- AuthenticationError,
- Repository,
-)
-from openhands.microagent.types import MicroagentContentResponse
-from openhands.server.routes.git import app as git_app
-from openhands.server.user_auth import (
- get_access_token,
- get_provider_tokens,
- get_user_id,
-)
-
-
-def test_client():
- """Create a test client for the git API."""
- app = FastAPI()
- app.include_router(git_app)
-
- @app.exception_handler(AuthenticationError)
- async def authentication_error_handler(request: Request, exc: AuthenticationError):
- return JSONResponse(
- status_code=401,
- content=str(exc),
- )
-
- # Override the FastAPI dependencies directly
- def mock_get_provider_tokens():
- return MappingProxyType(
- {
- ProviderType.GITHUB: ProviderToken(
- token=SecretStr('ghp_test_token'), host='github.com'
- ),
- ProviderType.GITLAB: ProviderToken(
- token=SecretStr('glpat_test_token'), host='gitlab.com'
- ),
- ProviderType.BITBUCKET: ProviderToken(
- token=SecretStr('bb_test_token'), host='bitbucket.org'
- ),
- }
- )
-
- def mock_get_access_token():
- return None
-
- def mock_get_user_id():
- return 'test_user'
-
- def mock_check_session_api_key():
- # Mock session API key check to always pass for tests
- return None
-
- # Override the dependencies in the app
- app.dependency_overrides[get_provider_tokens] = mock_get_provider_tokens
- app.dependency_overrides[get_access_token] = mock_get_access_token
- app.dependency_overrides[get_user_id] = mock_get_user_id
- app.dependency_overrides[check_session_api_key] = mock_check_session_api_key
-
- yield TestClient(app)
-
-
-def mock_github_repository():
- """Create a mock GitHub repository for testing."""
- return Repository(
- id='123456',
- full_name='test/repo',
- git_provider=ProviderType.GITHUB,
- is_public=True,
- stargazers_count=100,
- )
-
-
-def mock_gitlab_repository():
- """Create a mock GitLab repository for testing."""
- return Repository(
- id='123456',
- full_name='test/repo',
- git_provider=ProviderType.GITLAB,
- is_public=True,
- stargazers_count=100,
- )
-
-
-def mock_bitbucket_repository():
- """Create a mock Bitbucket repository for testing."""
- return Repository(
- id='123456',
- full_name='test/repo',
- git_provider=ProviderType.BITBUCKET,
- is_public=True,
- stargazers_count=100,
- )
-
-
-def sample_microagent_content():
- """Sample microagent file content."""
- return """---
-name: test_agent
-type: repo
-inputs:
- - name: query
- type: str
- description: Search query for the repository
-mcp_tools:
- stdio_servers:
- - name: git
- command: git
- - name: file_editor
- command: editor
----
-
-This is a test repository microagent for testing purposes."""
-
-
-def sample_cursorrules_content():
- """Sample .cursorrules file content."""
- return """---
-name: cursor_rules
-type: repo
----
-
-These are cursor rules for the repository."""
-
-
-class TestGetRepositoryMicroagents:
- """Test cases for the get_repository_microagents API endpoint."""
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagents_github_success(
- self,
- mock_provider_handler_cls,
- test_client,
- mock_github_repository,
- sample_microagent_content,
- sample_cursorrules_content,
- ):
- """Test successful retrieval of microagents from GitHub repository."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagents method to return sample data
- mock_provider_handler.get_microagents.return_value = [
- {
- 'name': 'test_agent',
- 'path': '.openhands/microagents/test_agent.md',
- 'created_at': '2024-01-01T00:00:00',
- },
- {
- 'name': 'cursorrules',
- 'path': '.cursorrules',
- 'created_at': '2024-01-01T00:00:00',
- },
- ]
-
- # Execute test
- response = test_client.get('/api/user/repository/test/repo/microagents')
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert len(data) == 2 # .cursorrules + 1 .md file
-
- # Check that basic fields are present (content is excluded for performance)
- for microagent in data:
- assert 'name' in microagent
- assert 'path' in microagent
- assert 'created_at' in microagent
- # Content field should not be present in listing API
- assert 'content' not in microagent
- # Type and other detailed fields are no longer included in listing API
- assert 'type' not in microagent
- assert 'triggers' not in microagent
- assert 'inputs' not in microagent
- assert 'tools' not in microagent
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagents_gitlab_success(
- self,
- mock_provider_handler_cls,
- test_client,
- mock_gitlab_repository,
- ):
- """Test successful retrieval of microagents from GitLab repository."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagents method to return sample data
- mock_provider_handler.get_microagents.return_value = [
- {
- 'name': 'test_agent',
- 'path': '.openhands/microagents/test_agent.md',
- 'created_at': '2024-01-01T00:00:00',
- }
- ]
-
- # Execute test
- response = test_client.get('/api/user/repository/test/repo/microagents')
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert len(data) == 1 # Only 1 .md file
- assert 'content' not in data[0] # Content should not be present in listing API
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagents_bitbucket_success(
- self,
- mock_provider_handler_cls,
- test_client,
- mock_bitbucket_repository,
- ):
- """Test successful retrieval of microagents from Bitbucket repository."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagents method to return sample data
- mock_provider_handler.get_microagents.return_value = [
- {
- 'name': 'test_agent',
- 'path': '.openhands/microagents/test_agent.md',
- 'created_at': '2024-01-01T00:00:00',
- }
- ]
-
- # Execute test
- response = test_client.get('/api/user/repository/test/repo/microagents')
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert len(data) == 1 # Only 1 .md file
- assert 'content' not in data[0] # Content should not be present in listing API
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagents_no_directory_found(
- self,
- mock_provider_handler_cls,
- test_client,
- mock_github_repository,
- ):
- """Test when microagents directory is not found."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagents method to return empty list
- mock_provider_handler.get_microagents.return_value = []
-
- # Execute test
- response = test_client.get('/api/user/repository/test/repo/microagents')
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert data == []
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagents_authentication_error(
- self,
- mock_provider_handler_cls,
- test_client,
- ):
- """Test authentication error."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagents method to raise AuthenticationError
- mock_provider_handler.get_microagents.side_effect = AuthenticationError(
- 'Invalid credentials'
- )
-
- # Execute test
- response = test_client.get('/api/user/repository/test/repo/microagents')
-
- # Assertions
- assert response.status_code == 401
- assert response.json() == 'Invalid credentials'
-
-
-class TestGetRepositoryMicroagentContent:
- """Test cases for the get_repository_microagent_content API endpoint."""
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagent_content_github_success(
- self,
- mock_provider_handler_cls,
- test_client,
- sample_microagent_content,
- ):
- """Test successful retrieval of microagent content from GitHub."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagent_content method
- mock_provider_handler.get_microagent_content.return_value = (
- MicroagentContentResponse(
- content=sample_microagent_content,
- path='.openhands/microagents/test_agent.md',
- triggers=['test', 'agent'],
- )
- )
-
- # Execute test
- file_path = '.openhands/microagents/test_agent.md'
- response = test_client.get(
- f'/api/user/repository/test/repo/microagents/content?file_path={quote(file_path)}'
- )
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert 'content' in data
- assert data['content'] == sample_microagent_content
- assert data['path'] == file_path
- assert 'triggers' in data
- assert data['triggers'] == ['test', 'agent']
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagent_content_gitlab_success(
- self,
- mock_provider_handler_cls,
- test_client,
- sample_microagent_content,
- ):
- """Test successful retrieval of microagent content from GitLab."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagent_content method
- mock_provider_handler.get_microagent_content.return_value = (
- MicroagentContentResponse(
- content=sample_microagent_content,
- path='.openhands/microagents/test_agent.md',
- triggers=['test', 'agent'],
- )
- )
-
- # Execute test
- file_path = '.openhands/microagents/test_agent.md'
- response = test_client.get(
- f'/api/user/repository/test/repo/microagents/content?file_path={quote(file_path)}'
- )
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert data['content'] == sample_microagent_content
- assert data['path'] == file_path
- assert 'triggers' in data
- assert data['triggers'] == ['test', 'agent']
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagent_content_bitbucket_success(
- self,
- mock_provider_handler_cls,
- test_client,
- sample_microagent_content,
- ):
- """Test successful retrieval of microagent content from Bitbucket."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagent_content method
- mock_provider_handler.get_microagent_content.return_value = (
- MicroagentContentResponse(
- content=sample_microagent_content,
- path='.openhands/microagents/test_agent.md',
- triggers=['test', 'agent'],
- )
- )
-
- # Execute test
- file_path = '.openhands/microagents/test_agent.md'
- response = test_client.get(
- f'/api/user/repository/test/repo/microagents/content?file_path={quote(file_path)}'
- )
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert data['content'] == sample_microagent_content
- assert data['path'] == file_path
- assert 'triggers' in data
- assert data['triggers'] == ['test', 'agent']
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagent_content_file_not_found(
- self,
- mock_provider_handler_cls,
- test_client,
- mock_github_repository,
- ):
- """Test when microagent file is not found."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagent_content method to raise RuntimeError
- mock_provider_handler.get_microagent_content.side_effect = RuntimeError(
- 'File not found'
- )
-
- # Execute test
- file_path = '.openhands/microagents/nonexistent.md'
- response = test_client.get(
- f'/api/user/repository/test/repo/microagents/content?file_path={quote(file_path)}'
- )
-
- # Assertions
- assert response.status_code == 500
- assert 'File not found' in response.json()
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagent_content_authentication_error(
- self,
- mock_provider_handler_cls,
- test_client,
- ):
- """Test authentication error for content API."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagent_content method to raise AuthenticationError
- mock_provider_handler.get_microagent_content.side_effect = AuthenticationError(
- 'Invalid credentials'
- )
-
- # Execute test
- file_path = '.openhands/microagents/test_agent.md'
- response = test_client.get(
- f'/api/user/repository/test/repo/microagents/content?file_path={quote(file_path)}'
- )
-
- # Assertions
- assert response.status_code == 401
- assert response.json() == 'Invalid credentials'
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagent_content_cursorrules(
- self,
- mock_provider_handler_cls,
- test_client,
- sample_cursorrules_content,
- ):
- """Test retrieval of .cursorrules file content."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagent_content method
- mock_provider_handler.get_microagent_content.return_value = (
- MicroagentContentResponse(
- content=sample_cursorrules_content,
- path='.cursorrules',
- triggers=['cursor', 'rules'],
- )
- )
-
- # Execute test
- file_path = '.cursorrules'
- response = test_client.get(
- f'/api/user/repository/test/repo/microagents/content?file_path={quote(file_path)}'
- )
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert data['content'] == sample_cursorrules_content
- assert data['path'] == file_path
- assert 'triggers' in data
- assert data['triggers'] == ['cursor', 'rules']
-
-
-class TestSpecialRepositoryStructures:
- """Test cases for special repository structures."""
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagents_openhands_repo_structure(
- self,
- mock_provider_handler_cls,
- test_client,
- ):
- """Test microagents from .openhands repository structure."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagents method to return sample data for .openhands repo
- mock_provider_handler.get_microagents.return_value = [
- {
- 'name': 'test_agent',
- 'path': 'microagents/test_agent.md', # Should be in microagents folder, not .openhands/microagents
- 'created_at': '2024-01-01T00:00:00',
- }
- ]
-
- # Execute test
- response = test_client.get('/api/user/repository/test/.openhands/microagents')
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert len(data) == 1
- assert (
- data[0]['path'] == 'microagents/test_agent.md'
- ) # Should be in microagents folder, not .openhands/microagents
-
- @pytest.mark.asyncio
- @patch('openhands.server.routes.git.ProviderHandler')
- async def test_get_microagents_gitlab_openhands_config_structure(
- self,
- mock_provider_handler_cls,
- test_client,
- ):
- """Test microagents from GitLab openhands-config repository structure."""
- # Setup mocks
- mock_provider_handler = AsyncMock()
- mock_provider_handler_cls.return_value = mock_provider_handler
-
- # Mock the get_microagents method to return sample data for openhands-config repo
- mock_provider_handler.get_microagents.return_value = [
- {
- 'name': 'test_agent',
- 'path': 'microagents/test_agent.md', # Should be in microagents folder, not .openhands/microagents
- 'created_at': '2024-01-01T00:00:00',
- }
- ]
-
- # Execute test
- response = test_client.get(
- '/api/user/repository/test/openhands-config/microagents'
- )
-
- # Assertions
- assert response.status_code == 200
- data = response.json()
- assert len(data) == 1
- assert (
- data[0]['path'] == 'microagents/test_agent.md'
- ) # Should be in microagents folder, not .openhands/microagents
diff --git a/tests/unit/server/routes/test_settings_store_functions.py b/tests/unit/server/routes/test_settings_store_functions.py
deleted file mode 100644
index fa82ac75d9..0000000000
--- a/tests/unit/server/routes/test_settings_store_functions.py
+++ /dev/null
@@ -1,610 +0,0 @@
-import os
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from fastapi import FastAPI
-from fastapi.testclient import TestClient
-from pydantic import SecretStr
-
-from openhands.app_server.errors import AuthError
-from openhands.app_server.secrets.secrets_router import check_provider_tokens
-from openhands.integrations.provider import ProviderToken
-from openhands.integrations.service_types import ProviderType
-from openhands.sdk.llm import LLM
-from openhands.sdk.settings import (
- AGENT_SETTINGS_SCHEMA_VERSION,
- AgentSettings,
- ConversationSettings,
-)
-from openhands.server.routes.secrets import (
- app as secrets_router,
-)
-from openhands.server.settings import POSTProviderModel
-from openhands.storage import get_file_store
-from openhands.storage.data_models.secrets import Secrets
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.secrets.file_secrets_store import FileSecretsStore
-
-_EXPOSE = {'expose_secrets': True}
-
-
-def _apply_settings_payload(
- payload: dict, existing_settings: Settings | None
-) -> Settings:
- """Test helper β€” mirrors the inlined logic in the settings route."""
- settings = existing_settings.model_copy() if existing_settings else Settings()
- settings.update(payload)
- return settings
-
-
-_DEFAULT_LLM = LLM(model='test-model')
-
-
-def _make_settings(llm: LLM | None = None) -> Settings:
- """Helper to create Settings with an AgentSettings object."""
- return Settings(agent_settings=AgentSettings(llm=llm or _DEFAULT_LLM))
-
-
-def _secret(s: SecretStr | None) -> str | None:
- """Unwrap a SecretStr to its plain value."""
- return s.get_secret_value() if s is not None else None
-
-
-def _persisted(settings: Settings) -> dict:
- """Dump agent_settings with secrets exposed for persistence assertions."""
- return settings.agent_settings.model_dump(mode='json', context=_EXPOSE)
-
-
[email protected](autouse=True)
-def allow_short_context_windows():
- with patch.dict(os.environ, {'ALLOW_SHORT_CONTEXT_WINDOWS': 'true'}, clear=False):
- yield
-
-
-async def get_settings_store(request):
- """Mock function to get settings store."""
- return MagicMock()
-
-
-def test_client():
- # Create a test client with a FastAPI app that includes the secrets router
- # This is necessary because TestClient with APIRouter directly doesn't set up
- # the full middleware stack in newer FastAPI versions (0.118.0+)
- test_app = FastAPI()
- test_app.include_router(secrets_router)
-
- with (
- patch.dict(os.environ, {'SESSION_API_KEY': ''}, clear=False),
- patch('openhands.app_server.utils.dependencies._SESSION_API_KEY', None),
- patch(
- 'openhands.app_server.secrets.secrets_router.check_provider_tokens',
- AsyncMock(return_value=None),
- ),
- ):
- client = TestClient(test_app)
- yield client
-
-
-def temp_dir(tmp_path_factory: pytest.TempPathFactory) -> str:
- return str(tmp_path_factory.mktemp('secrets_store'))
-
-
-def file_secrets_store(temp_dir):
- file_store = get_file_store('local', temp_dir)
- store = FileSecretsStore(file_store)
- with patch(
- 'openhands.storage.secrets.file_secrets_store.FileSecretsStore.get_instance',
- AsyncMock(return_value=store),
- ):
- yield store
-
-
-# Tests for check_provider_tokens
-async def test_check_provider_tokens_valid():
- """Test check_provider_tokens with valid tokens."""
- provider_token = ProviderToken(token=SecretStr('valid-token'))
- providers = POSTProviderModel(provider_tokens={ProviderType.GITHUB: provider_token})
-
- # Empty existing provider tokens
- existing_provider_tokens = {}
-
- # Mock the validate_provider_token function to return GITHUB for valid tokens
- with patch(
- 'openhands.app_server.secrets.secrets_router.validate_provider_token'
- ) as mock_validate:
- mock_validate.return_value = ProviderType.GITHUB
-
- await check_provider_tokens(providers, existing_provider_tokens)
- mock_validate.assert_called_once()
-
-
-async def test_check_provider_tokens_invalid():
- """Test check_provider_tokens with invalid tokens."""
- provider_token = ProviderToken(token=SecretStr('invalid-token'))
- providers = POSTProviderModel(provider_tokens={ProviderType.GITHUB: provider_token})
-
- # Empty existing provider tokens
- existing_provider_tokens = {}
-
- # Mock the validate_provider_token function to return None for invalid tokens
- with patch(
- 'openhands.app_server.secrets.secrets_router.validate_provider_token'
- ) as mock_validate:
- mock_validate.return_value = None
-
- with pytest.raises(AuthError):
- await check_provider_tokens(providers, existing_provider_tokens)
-
- mock_validate.assert_called_once()
-
-
-async def test_check_provider_tokens_wrong_type():
- """Test check_provider_tokens with unsupported provider type."""
- providers = POSTProviderModel(provider_tokens={})
- existing_provider_tokens = {}
-
- await check_provider_tokens(providers, existing_provider_tokens)
-
-
-async def test_check_provider_tokens_no_tokens():
- """Test check_provider_tokens with no tokens."""
- providers = POSTProviderModel(provider_tokens={})
- existing_provider_tokens = {}
-
- await check_provider_tokens(providers, existing_provider_tokens)
-
-
-# Tests for _apply_settings_payload (SDK-first settings)
-def test_apply_payload_sdk_keys_stored_and_readable():
- """Nested SDK keys should be stored in agent_settings and readable via properties."""
- payload = {
- 'agent_settings': {
- 'llm': {
- 'model': 'gpt-4',
- 'api_key': 'test-api-key',
- 'base_url': 'https://api.example.com',
- }
- },
- }
-
- result = _apply_settings_payload(payload, None)
-
- assert _persisted(result)['llm']['model'] == 'gpt-4'
- assert _persisted(result)['llm']['api_key'] == 'test-api-key'
- assert _persisted(result)['llm']['base_url'] == 'https://api.example.com'
- # Properties read from agent_settings
- assert result.agent_settings.llm.model == 'gpt-4'
- assert _secret(result.agent_settings.llm.api_key) == 'test-api-key'
- assert result.agent_settings.llm.base_url == 'https://api.example.com'
-
-
-def test_apply_payload_updates_existing():
- """Nested SDK keys should update existing settings."""
- existing = _make_settings(
- LLM(
- model='gpt-3.5',
- api_key=SecretStr('old-api-key'),
- base_url='https://old.example.com',
- )
- )
-
- payload = {
- 'agent_settings': {
- 'llm': {
- 'model': 'gpt-4',
- 'api_key': 'new-api-key',
- 'base_url': 'https://new.example.com',
- }
- },
- }
-
- result = _apply_settings_payload(payload, existing)
-
- assert result.agent_settings.llm.model == 'gpt-4'
- assert _secret(result.agent_settings.llm.api_key) == 'new-api-key'
- assert result.agent_settings.llm.base_url == 'https://new.example.com'
-
-
-def test_apply_payload_preserves_secrets_when_not_provided():
- """When the API key is not in the payload, the existing value is preserved."""
- existing = _make_settings(
- LLM(model='gpt-3.5', api_key=SecretStr('existing-api-key'))
- )
-
- payload = {'agent_settings': {'llm': {'model': 'gpt-4'}}}
-
- result = _apply_settings_payload(payload, existing)
-
- assert result.agent_settings.llm.model == 'gpt-4'
- assert _secret(result.agent_settings.llm.api_key) == 'existing-api-key'
- assert result.agent_settings.llm.base_url is None
-
-
-def test_apply_payload_mcp_update_preserves_existing_llm_settings():
- existing_settings = Settings(
- agent_settings=AgentSettings(
- llm=LLM(
- model='anthropic/claude-sonnet-4-5-20250929',
- api_key=SecretStr('existing-api-key'),
- base_url='https://my-custom-proxy.example.com',
- )
- ),
- )
-
- result = _apply_settings_payload(
- {
- 'agent_settings': {
- 'mcp_config': {
- 'stdio_servers': [
- {
- 'name': 'my-server',
- 'command': 'npx',
- 'args': ['-y', '@my/mcp-server'],
- 'env': {
- 'API_TOKEN': 'secret123',
- 'ENDPOINT': 'https://example.com',
- },
- }
- ]
- }
- }
- },
- existing_settings,
- )
-
- assert result.agent_settings.llm.model == 'anthropic/claude-sonnet-4-5-20250929'
- assert _secret(result.agent_settings.llm.api_key) == 'existing-api-key'
- assert result.agent_settings.llm.base_url == 'https://my-custom-proxy.example.com'
-
-
-def test_apply_payload_clears_secrets_when_explicitly_null_or_empty():
- """Explicit null/empty secret values should clear existing SDK secrets."""
- existing = _make_settings(
- LLM(
- model='anthropic/claude-sonnet-4-5-20250929',
- api_key=SecretStr('existing-api-key'),
- )
- )
-
- payload = {'agent_settings': {'llm': {'api_key': None}}}
- result = _apply_settings_payload(payload, existing)
- assert result.agent_settings.llm.api_key is None
-
- payload = {'agent_settings': {'llm': {'api_key': ''}}}
- result = _apply_settings_payload(payload, existing)
- assert result.agent_settings.llm.api_key is None
-
-
-def test_apply_payload_preserves_explicit_null_non_secret_sdk_resets():
- """Explicit null non-secret SDK values should survive for inherited-settings clearing."""
- existing = _make_settings(
- LLM(model='openai/gpt-4o', base_url='https://custom.example/v1')
- )
-
- result = _apply_settings_payload(
- {'agent_settings': {'llm': {'base_url': None}}}, existing
- )
-
- assert result.agent_settings.llm.base_url is None
- assert _persisted(result)['llm']['base_url'] is None
-
-
-def test_apply_payload_mcp_preserves_llm_settings():
- """Non-LLM payloads (e.g. MCP config) should not affect existing LLM settings."""
- existing = _make_settings(
- LLM(
- model='anthropic/claude-sonnet-4-5-20250929',
- api_key=SecretStr('existing-api-key'),
- base_url='https://my-custom-proxy.example.com',
- )
- )
-
- payload = {
- 'agent_settings': {
- 'mcp_config': {
- 'stdio_servers': [
- {
- 'name': 'my-server',
- 'command': 'npx',
- 'args': ['-y', '@my/mcp-server'],
- }
- ],
- },
- },
- }
-
- result = _apply_settings_payload(payload, existing)
-
- assert result.agent_settings.llm.model == 'anthropic/claude-sonnet-4-5-20250929'
- assert _secret(result.agent_settings.llm.api_key) == 'existing-api-key'
- assert result.agent_settings.llm.base_url == 'https://my-custom-proxy.example.com'
-
-
-def test_apply_payload_non_sdk_flat_keys_applied():
- """Non-SDK flat keys (language, git, etc.) should still be applied normally."""
- payload = {
- 'language': 'ja',
- 'git_user_name': 'test-user',
- }
-
- result = _apply_settings_payload(payload, None)
-
- assert result.language == 'ja'
- assert result.git_user_name == 'test-user'
-
-
-def test_apply_payload_conversation_settings_stored_top_level():
- """Conversation security settings should be applied as top-level Settings fields."""
- payload = {
- 'conversation_settings': {
- 'confirmation_mode': True,
- 'security_analyzer': 'llm',
- },
- }
-
- result = _apply_settings_payload(payload, None)
-
- assert result.conversation_settings.confirmation_mode is True
- assert result.conversation_settings.security_analyzer == 'llm'
- assert not hasattr(result.agent_settings, 'confirmation_mode')
-
-
-def test_agent_settings_construction():
- """Settings constructed with proper objects should be accessible."""
- s = Settings(
- agent_settings=AgentSettings(
- llm=LLM(
- model='gpt-4',
- api_key=SecretStr('my-key'),
- base_url='https://example.com',
- ),
- agent='CodeActAgent',
- ),
- conversation_settings=ConversationSettings(confirmation_mode=True),
- )
-
- assert _persisted(s)['llm']['model'] == 'gpt-4'
- assert _persisted(s)['llm']['api_key'] == 'my-key'
- assert _persisted(s)['llm']['base_url'] == 'https://example.com'
- assert _persisted(s)['agent'] == 'CodeActAgent'
- assert s.conversation_settings.confirmation_mode is True
- assert s.agent_settings.llm.model == 'gpt-4'
- assert s.agent_settings.agent == 'CodeActAgent'
-
-
-def test_agent_settings_normalized_with_schema_version_and_extras():
- s = Settings(
- agent_settings=AgentSettings(
- llm=LLM(model='anthropic/claude-sonnet-4-5-20250929'),
- ),
- conversation_settings=ConversationSettings(
- max_iterations=64,
- confirmation_mode=True,
- ),
- )
-
- dump = s.agent_settings.model_dump(mode='json', context={'expose_secrets': True})
- assert dump['schema_version'] == AGENT_SETTINGS_SCHEMA_VERSION
- assert _persisted(s)['llm']['model'] == 'anthropic/claude-sonnet-4-5-20250929'
- assert s.conversation_settings.confirmation_mode is True
- assert s.conversation_settings.max_iterations == 64
-
-
-def test_agent_settings_persistence_strips_secret_values():
- s = Settings(
- agent_settings=AgentSettings(
- llm=LLM(
- model='anthropic/claude-sonnet-4-5-20250929',
- api_key=SecretStr('super-secret'),
- ),
- ),
- conversation_settings=ConversationSettings(max_iterations=64),
- )
-
- persisted = s.agent_settings.model_dump(mode='json')
- # Secrets are redacted by default (not exposed)
- assert persisted['schema_version'] == AGENT_SETTINGS_SCHEMA_VERSION
- assert persisted['llm']['model'] == 'anthropic/claude-sonnet-4-5-20250929'
- assert 'max_iterations' not in persisted
- assert persisted['llm']['api_key'] == '**********'
- assert s.conversation_settings.max_iterations == 64
-
-
-def test_openhands_model_settings_remain_user_facing():
- s = Settings(
- agent_settings=AgentSettings(
- llm=LLM(model='openhands/claude-opus-4-5-20251101')
- )
- )
-
- assert _persisted(s)['llm']['model'] == 'litellm_proxy/claude-opus-4-5-20251101'
- api_data = s.get_agent_settings_display()
- assert api_data['llm']['model'] == 'openhands/claude-opus-4-5-20251101'
-
-
-def test_litellm_proxy_model_settings_migrate_back_to_openhands_prefix():
- s = Settings(
- agent_settings=AgentSettings(
- llm=LLM(model='litellm_proxy/claude-opus-4-5-20251101')
- )
- )
-
- assert _persisted(s)['llm']['model'] == 'litellm_proxy/claude-opus-4-5-20251101'
- api_data = s.get_agent_settings_display()
- assert api_data['llm']['model'] == 'openhands/claude-opus-4-5-20251101'
-
-
-# ──────────────────────────────────────────────────────────────────
-# Regression tests for openhands/ β†’ litellm_proxy/ round-trip bug
-# ──────────────────────────────────────────────────────────────────
-# The SDK's AgentSettings.model_validate automatically transforms
-# "openhands/X" β†’ "litellm_proxy/X" with a proxy base_url. The
-# settings router must convert it back for the frontend and handle
-# the internal model name in is_openhands_model-style checks.
-
-
-def test_post_merge_llm_fixups_handles_openhands_model_after_sdk_transform():
- """After SDK transforms openhands/X β†’ litellm_proxy/X with a base_url,
- _post_merge_llm_fixups should recognise it as a managed model and not
- clobber the base_url with a provider lookup."""
- from openhands.app_server.settings.settings_router import _post_merge_llm_fixups
-
- # Simulate: user sends openhands/claude-opus-4-5, sdk transforms it
- settings = Settings()
- settings.update({'agent_settings': {'llm': {'model': 'openhands/claude-opus-4-5'}}})
-
- # After SDK transform:
- assert settings.agent_settings.llm.model == 'litellm_proxy/claude-opus-4-5'
- assert settings.agent_settings.llm.base_url is not None # SDK set it
-
- # _post_merge_llm_fixups should NOT break the base_url
- _post_merge_llm_fixups(settings)
- assert settings.agent_settings.llm.base_url is not None
-
-
-def test_post_merge_llm_fixups_sets_proxy_url_for_openhands_model_with_null_base_url():
- """When an openhands model ends up with a null base_url (edge case from
- older storage), _post_merge_llm_fixups should set the proxy URL."""
- from openhands.app_server.settings.settings_router import (
- LITE_LLM_API_URL,
- _post_merge_llm_fixups,
- )
-
- settings = Settings(
- agent_settings=AgentSettings(
- llm=LLM(model='litellm_proxy/claude-opus-4-5', base_url=None)
- ),
- )
- # Force base_url to None (bypass SDK validator for this edge case)
- settings.agent_settings.llm.base_url = None
-
- _post_merge_llm_fixups(settings)
-
- # Should recognise litellm_proxy/ as a managed model and set the URL
- assert settings.agent_settings.llm.base_url == LITE_LLM_API_URL
-
-
-def test_get_agent_settings_display_clears_proxy_base_url():
- """get_agent_settings_display should clear the LiteLLM proxy base_url
- for openhands models so the frontend sees null (enabling basic mode)."""
- s = Settings(
- agent_settings=AgentSettings(llm=LLM(model='openhands/claude-opus-4-5'))
- )
-
- # SDK sets the proxy URL internally
- assert s.agent_settings.llm.base_url is not None
-
- display = s.get_agent_settings_display()
- # Model name should be converted back
- assert display['llm']['model'] == 'openhands/claude-opus-4-5'
- # Proxy base_url should be cleared for display
- assert display['llm']['base_url'] is None
-
-
-def test_save_then_display_roundtrip_openhands_model():
- """Full round-trip: save openhands model via update(), then display it.
- The frontend should see openhands/X with null base_url (basic mode)."""
- # Simulate save
- settings = Settings()
- settings.update(
- {
- 'agent_settings': {
- 'llm': {
- 'model': 'openhands/claude-opus-4-5',
- 'api_key': '',
- 'base_url': None,
- }
- }
- }
- )
-
- # Verify internal representation
- assert settings.agent_settings.llm.model == 'litellm_proxy/claude-opus-4-5'
-
- # Simulate load response
- display = settings.get_agent_settings_display()
- assert display['llm']['model'] == 'openhands/claude-opus-4-5'
- assert display['llm']['base_url'] is None
-
-
-# Tests for store_provider_tokens
-async def test_store_provider_tokens_new_tokens(test_client, file_secrets_store):
- """Test store_provider_tokens with new tokens."""
- provider_tokens = {'provider_tokens': {'github': {'token': 'new-token'}}}
-
- # Mock the settings store
- mock_store = MagicMock()
- mock_store.load = AsyncMock(return_value=None) # No existing settings
-
- Secrets()
-
- user_secrets = await file_secrets_store.store(Secrets())
-
- response = test_client.post('/api/add-git-providers', json=provider_tokens)
- assert response.status_code == 200
-
- user_secrets = await file_secrets_store.load()
-
- assert (
- user_secrets.provider_tokens[ProviderType.GITHUB].token.get_secret_value()
- == 'new-token'
- )
-
-
-async def test_store_provider_tokens_update_existing(test_client, file_secrets_store):
- """Test store_provider_tokens updates existing tokens."""
- # Create existing settings with a GitHub token
- github_token = ProviderToken(token=SecretStr('old-token'))
- provider_tokens = {ProviderType.GITHUB: github_token}
-
- # Create a Secrets with the provider tokens
- user_secrets = Secrets(provider_tokens=provider_tokens)
-
- await file_secrets_store.store(user_secrets)
-
- response = test_client.post(
- '/api/add-git-providers',
- json={'provider_tokens': {'github': {'token': 'updated-token'}}},
- )
-
- assert response.status_code == 200
-
- user_secrets = await file_secrets_store.load()
-
- assert (
- user_secrets.provider_tokens[ProviderType.GITHUB].token.get_secret_value()
- == 'updated-token'
- )
-
-
-async def test_store_provider_tokens_keep_existing(test_client, file_secrets_store):
- """Test store_provider_tokens keeps existing tokens when empty string provided."""
- # Create existing secrets with a GitHub token
- github_token = ProviderToken(token=SecretStr('existing-token'))
- provider_tokens = {ProviderType.GITHUB: github_token}
- user_secrets = Secrets(provider_tokens=provider_tokens)
-
- await file_secrets_store.store(user_secrets)
-
- response = test_client.post(
- '/api/add-git-providers',
- json={'provider_tokens': {'github': {'token': ''}}},
- )
- assert response.status_code == 200
-
- user_secrets = await file_secrets_store.load()
-
- assert (
- user_secrets.provider_tokens[ProviderType.GITHUB].token.get_secret_value()
- == 'existing-token'
- )
diff --git a/tests/unit/server/routes/test_start_endpoint.py b/tests/unit/server/routes/test_start_endpoint.py
deleted file mode 100644
index 3581523445..0000000000
--- a/tests/unit/server/routes/test_start_endpoint.py
+++ /dev/null
@@ -1,150 +0,0 @@
-"""Tests for /start endpoint provider token handling."""
-
-from types import MappingProxyType
-from unittest.mock import AsyncMock, patch
-
-import pytest
-from pydantic import SecretStr
-
-from openhands.integrations.provider import ProviderToken, ProviderType
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.routes.manage_conversations import (
- ProvidersSetModel,
- start_conversation,
-)
-from openhands.server.types import AppMode
-from openhands.storage.data_models.conversation_metadata import ConversationMetadata
-from openhands.storage.data_models.conversation_status import ConversationStatus
-from openhands.storage.data_models.settings import Settings
-
-
-def mock_settings():
- """Create a real Settings object with minimal required fields."""
- return Settings(
- language='en',
- agent='CodeActAgent',
- max_iterations=100,
- llm_model='anthropic/claude-3-5-sonnet-20241022',
- llm_api_key=SecretStr('test_api_key_12345'),
- llm_base_url=None,
- )
-
-
-def mock_provider_tokens():
- """Create real provider tokens to test with."""
- return MappingProxyType(
- {
- ProviderType.GITHUB: ProviderToken(
- token=SecretStr('ghp_real_token_test123'), user_id='test_user_456'
- )
- }
- )
-
-
-def mock_conversation_metadata():
- """Create a real ConversationMetadata object."""
- return ConversationMetadata(
- conversation_id='test_conv_123',
- user_id='test_user_456',
- title='Test Conversation',
- selected_repository='test/repo',
- selected_branch='main',
- git_provider=ProviderType.GITHUB,
- )
-
-
-async def test_start_endpoint_passes_provider_tokens(
- mock_settings, mock_provider_tokens, mock_conversation_metadata
-):
- """Test that /start endpoint passes provider_tokens to setup_init_conversation_settings.
-
- This test verifies the full end-to-end flow with real tokens through to ConversationInitData.
- """
- conversation_id = 'test_conv_123'
- user_id = 'test_user_456'
- providers_set = ProvidersSetModel(providers_set=[ProviderType.GITHUB])
-
- # Mock conversation store
- mock_conversation_store = AsyncMock()
- mock_conversation_store.get_metadata = AsyncMock(
- return_value=mock_conversation_metadata
- )
-
- # Mock agent loop info that will be returned
- mock_agent_loop_info = AgentLoopInfo(
- conversation_id=conversation_id,
- url=None,
- session_api_key=None,
- event_store=None,
- status=ConversationStatus.RUNNING,
- )
-
- # Mock only infrastructure - let setup_init_conversation_settings run for real
- with patch(
- 'openhands.server.routes.manage_conversations.conversation_manager'
- ) as mock_manager:
- # Mock the stores that setup_init_conversation_settings needs
- with patch(
- 'openhands.server.services.conversation_service.SettingsStoreImpl.get_instance'
- ) as mock_settings_store_cls:
- with patch(
- 'openhands.server.services.conversation_service.SecretsStoreImpl.get_instance'
- ) as mock_secrets_store_cls:
- with patch(
- 'openhands.server.services.conversation_service.server_config'
- ) as mock_server_config:
- # Setup store mocks
- mock_settings_store = AsyncMock()
- mock_settings_store.load = AsyncMock(return_value=mock_settings)
- mock_settings_store_cls.return_value = mock_settings_store
-
- mock_secrets_store = AsyncMock()
- mock_secrets_store.load = AsyncMock(return_value=None)
- mock_secrets_store_cls.return_value = mock_secrets_store
-
- mock_server_config.app_mode = AppMode.SAAS
-
- mock_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
-
- # Call endpoint with provider tokens
- response = await start_conversation(
- providers_set=providers_set,
- conversation_id=conversation_id,
- user_id=user_id,
- provider_tokens=mock_provider_tokens,
- settings=mock_settings,
- conversation_store=mock_conversation_store,
- )
-
- # Verify ConversationInitData has real provider tokens
- mock_manager.maybe_start_agent_loop.assert_called_once()
- call_kwargs = mock_manager.maybe_start_agent_loop.call_args[1]
- conversation_init_data = call_kwargs['settings']
-
- assert conversation_init_data.git_provider_tokens is not None
- assert (
- conversation_init_data.git_provider_tokens
- == mock_provider_tokens
- )
- assert (
- ProviderType.GITHUB
- in conversation_init_data.git_provider_tokens
- )
-
- github_token = conversation_init_data.git_provider_tokens[
- ProviderType.GITHUB
- ]
- assert (
- github_token.token.get_secret_value()
- == 'ghp_real_token_test123'
- )
- assert github_token.user_id == 'test_user_456'
-
- assert response.status == 'ok'
- assert response.conversation_id == conversation_id
diff --git a/tests/unit/server/test_openapi_schema_generation.py b/tests/unit/server/test_openapi_schema_generation.py
index 868776a7e9..8a3f8ad8f7 100644
--- a/tests/unit/server/test_openapi_schema_generation.py
+++ b/tests/unit/server/test_openapi_schema_generation.py
@@ -106,5 +106,5 @@ async def test_openapi_schema_generation(test_client):
assert json_str is not None
# Optionally, you can check for specific endpoints if needed
- assert '/api/settings' in schema['paths']
+ assert '/api/v1/settings' in schema['paths']
assert '/health' in schema['paths']