before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
import uuid
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from pydantic import SecretStr
from sqlalchemy.exc import IntegrityError
# Mock the database module before importing OrgStore
with patch('storage.database.engine', create=True), patch(
'storage.database.a_engine', create=True
):
f... | 🟠 **Important**: Test verifies deletion succeeds but does NOT verify invitations are actually deleted.
The comment says "SQLite doesn't enforce CASCADE by default", which means this test might pass even if CASCADE fails. Add an assertion that invitations are cleaned up:
```suggestion
# Assert - Organization shou... | session.flush()
# Create a second org for the user's current_org_id
# (to avoid the user.current_org_id constraint issue during deletion)
other_org = Org(id=other_org_id, name='other-org')
session.add(other_org)
session.flush()
# Create user with current_org poi... | @@ -806,3 +807,88 @@ def test_orphaned_user_error_contains_user_ids():
assert error.user_ids == user_ids
assert '2 user(s)' in str(error)
assert 'no remaining organization' in str(error)
+
+
+def test_org_deletion_with_invitations_uses_passive_deletes(
+ session_maker, mock_litellm_api
+):
+ """
+ ... | enterprise/tests/unit/test_org_store.py | 26 | Python | 0.857 | bug | 798 | 809 | 49 | false | fix(backend): unable to delete an organization after inviting at least one member | 12,993 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
enable_default_condenser = Column(Boolean, nullable=False, default=True)
billing_margin = Column(Float, nullable=True, default=DEFAULT_BILLING_MARGIN)
enable_proactive_conversation_starters = Column(
Boolean, nullable=False, default=True
)
sandbox_base_container_image = Column(String, nullab... | 🟡 **Suggestion**: Why only `invitations`? Do other relationships need investigation?
Looking at this file, I see:
- `org_members` - no passive_deletes
- `current_users` - no passive_deletes
- `billing_sessions` - no passive_deletes
- `stored_conversation_metadata_saas` - no passive_deletes
Are these foreign keys n... | enable_default_condenser = Column(Boolean, nullable=False, default=True)
billing_margin = Column(Float, nullable=True, default=DEFAULT_BILLING_MARGIN)
enable_proactive_conversation_starters = Column(
Boolean, nullable=False, default=True
)
sandbox_base_container_image = Column(String, nullab... | @@ -51,7 +51,9 @@ class Org(Base): # type: ignore
# Relationships
org_members = relationship('OrgMember', back_populates='org')
current_users = relationship('User', back_populates='current_org')
- invitations = relationship('OrgInvitation', back_populates='org')
+ invitations = relationship(
+ ... | enterprise/storage/org.py | 26 | Python | 0.786 | bug | 528 | 51 | 51 | false | fix(backend): unable to delete an organization after inviting at least one member | 12,993 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import uuid
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from pydantic import SecretStr
from sqlalchemy.exc import IntegrityError
# Mock the database module before importing OrgStore
with patch('storage.database.engine', create=True), patch(
'storage.database.a_engine', create=True
):
f... | 🟢 **Nit**: Excellent docstring. This is how you explain the "why" of a test - describes the bug, the symptom, and the mechanism. Well done. |
# Act
error = OrphanedUserError(user_ids)
# Assert
assert error.user_ids == user_ids
assert '2 user(s)' in str(error)
assert 'no remaining organization' in str(error)
def test_org_deletion_with_invitations_uses_passive_deletes(
session_maker, mock_litellm_api
):
"""
GIVEN: Organi... | @@ -806,3 +807,88 @@ def test_orphaned_user_error_contains_user_ids():
assert error.user_ids == user_ids
assert '2 user(s)' in str(error)
assert 'no remaining organization' in str(error)
+
+
+def test_org_deletion_with_invitations_uses_passive_deletes(
+ session_maker, mock_litellm_api
+):
+ """
+ ... | enterprise/tests/unit/test_org_store.py | 26 | Python | 0.5 | bug | 139 | 809 | 51 | false | fix(backend): unable to delete an organization after inviting at least one member | 12,993 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
owner_role,
member_role,
):
"""Test that an owner can successfully remove a regular user."""
# Arrange
with (
patch(
'server.services.org_member_service.OrgMemberStore.get_org_member'
) as mock_get_member,
patch(
... | 🟠 **Important**: Mocking `get_user_by_id` to return `None` in all existing tests bypasses your new logic entirely. These tests no longer verify that the current_org_id update works correctly in normal scenarios.
Better approach: Mock users with a `current_org_id` that differs from the removed org, so the tests verify... | owner_role,
member_role,
):
"""Test that an owner can successfully remove a regular user."""
# Arrange
with (
patch(
'server.services.org_member_service.OrgMemberStore.get_org_member'
) as mock_get_member,
patch(
... | @@ -549,13 +549,17 @@ async def test_owner_removes_user_succeeds(
patch(
'server.services.org_member_service.OrgMemberStore.remove_user_from_org'
) as mock_remove,
+ patch(
+ 'server.services.org_member_service.UserStore.get_user_by_id'
+ )... | enterprise/tests/unit/server/services/test_org_member_service.py | 26 | Python | 0.643 | bug | 478 | 51 | 51 | false | fix(backend): update current_org_id when removing a member from an organization | 12,995 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
target_role = RoleStore.get_role_by_id(target_membership.role_id)
if not requester_role or not target_role:
return False, 'role_not_found'
# Check permission based on roles
if not OrgMemberService._can_remove_member(
requester_role.name, ... | 🟡 **Suggestion**: Type inconsistency - first param is `str(target_user_id)`, second is `target_user_id` as UUID. While this may match the API signature, it creates confusion.
Consider making `update_current_org` accept consistent types, or add a comment explaining why the string conversion is needed. The personal wor... | target_role = RoleStore.get_role_by_id(target_membership.role_id)
if not requester_role or not target_role:
return False, 'role_not_found'
# Check permission based on roles
if not OrgMemberService._can_remove_member(
requester_role.name, ... | @@ -168,6 +168,12 @@ def _remove_member():
if not success:
return False, 'removal_failed'
+ # Update user's current_org_id if it points to the org they were removed from
+ user = UserStore.get_user_by_id(str(target_user_id))
+ if user and user.current_org... | enterprise/server/services/org_member_service.py | 26 | Python | 0.786 | suggestion | 419 | 51 | 51 | false | fix(backend): update current_org_id when removing a member from an organization | 12,995 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
target_role = RoleStore.get_role_by_id(target_membership.role_id)
if not requester_role or not target_role:
return False, 'role_not_found'
# Check permission based on roles
if not OrgMemberService._can_remove_member(
requester_role.name, ... | 🟢 **Nit**: Good defensive check with `if user and user.current_org_id == org_id`. The None check prevents errors if the user was somehow deleted, and the org_id check ensures you only update when necessary. Clean implementation. | target_role = RoleStore.get_role_by_id(target_membership.role_id)
if not requester_role or not target_role:
return False, 'role_not_found'
# Check permission based on roles
if not OrgMemberService._can_remove_member(
requester_role.name, ... | @@ -168,6 +168,12 @@ def _remove_member():
if not success:
return False, 'removal_failed'
+ # Update user's current_org_id if it points to the org they were removed from
+ user = UserStore.get_user_by_id(str(target_user_id))
+ if user and user.current_org... | enterprise/server/services/org_member_service.py | 26 | Python | 0.786 | suggestion | 228 | 51 | 51 | false | fix(backend): update current_org_id when removing a member from an organization | 12,995 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
async def test_owner_updates_user_to_admin_succeeds(
self,
org_id,
current_user_id,
target_user_id,
requester_membership_owner,
target_membership_user,
owner_role,
member_role,
admin_role,
):
"""GIVEN owner and target user WHEN owne... | 🔴 **Critical - Mocks Aren't Tests**: These tests only assert that mocked functions were called with the right arguments. They don't test actual behavior:
- Won't catch bugs in LiteLLM integration
- Won't verify error handling actually works
- Won't prove the re-invite issue is fixed
Per enterprise testing guidelines... | patch(
'server.services.org_member_service.UserStore.get_user_by_id'
) as mock_get_user,
patch(
'server.services.org_member_service.LiteLlmManager.remove_user_from_team',
new_callable=AsyncMock,
) as mock_litellm_remove,
... | @@ -990,6 +990,141 @@ async def test_removal_failed_returns_error(
assert success is False
assert error == 'removal_failed'
+ @pytest.mark.asyncio
+ async def test_successful_removal_calls_litellm_remove_user_from_team(
+ self,
+ org_id,
+ current_user_id,
+ ... | enterprise/tests/unit/server/services/test_org_member_service.py | 26 | Python | 0.786 | bug | 673 | 51 | 51 | false | fix(backend): ensure members are removed from the corresponding litellm team when removed from an organization | 12,996 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
await LiteLlmManager.remove_user_from_team(
str(target_user_id), str(org_id)
)
logger.info(
'Successfully removed user from LiteLLM team',
extra={
'user_id': str(target_user_id),
... | 🟡 **Suggestion**: The comment says "LiteLLM state will be eventually consistent" but there's no retry mechanism. Consider:
1. Adding a background job to retry failed removals, OR
2. Documenting why eventual consistency is acceptable here (e.g., "Access is controlled by database; LiteLLM is cache-like"), OR
3. Makin... |
success, error = await call_sync_from_async(_remove_member)
# If database removal succeeded, also remove from LiteLLM team
if success:
try:
await LiteLlmManager.remove_user_from_team(
str(target_user_id), str(org_id)
)
... | @@ -170,7 +172,34 @@ def _remove_member():
return True, None
- return await call_sync_from_async(_remove_member)
+ success, error = await call_sync_from_async(_remove_member)
+
+ # If database removal succeeded, also remove from LiteLLM team
+ if success:
+ try:
+... | enterprise/server/services/org_member_service.py | 26 | Python | 0.5 | bug | 486 | 51 | 51 | false | fix(backend): ensure members are removed from the corresponding litellm team when removed from an organization | 12,996 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
return False, 'cannot_remove_last_owner'
# Perform the removal
success = OrgMemberStore.remove_user_from_org(org_id, target_user_id)
if not success:
return False, 'removal_failed'
return True, None
success, error = await call... | 🟢 **Good**: Pragmatic error handling - the operation succeeds even if LiteLLM cleanup fails. This prevents blocking user operations due to external service issues. The database is the source of truth. | return False, 'cannot_remove_last_owner'
# Perform the removal
success = OrgMemberStore.remove_user_from_org(org_id, target_user_id)
if not success:
return False, 'removal_failed'
# Update user's current_org_id if it points to the org... | @@ -170,7 +172,34 @@ def _remove_member():
return True, None
- return await call_sync_from_async(_remove_member)
+ success, error = await call_sync_from_async(_remove_member)
+
+ # If database removal succeeded, also remove from LiteLLM team
+ if success:
+ try:
+... | enterprise/server/services/org_member_service.py | 26 | Python | 0.643 | bug | 200 | 51 | 51 | false | fix(backend): ensure members are removed from the corresponding litellm team when removed from an organization | 12,996 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import asyncio
import os
from abc import ABC, abstractmethod
from openhands.agent_server import env_parser
from openhands.app_server.errors import SandboxError
from openhands.app_server.sandbox.sandbox_spec_models import (
SandboxSpecInfo,
SandboxSpecInfoPage,
)
from openhands.app_server.services.injector impo... | 🟠 **Important**: Why this specific agent-server image?
You changed from `61470a1-python` to `010e847-python` with zero explanation. These look like git commit SHAs, but:
- What commit is `010e847`?
- Is this image tested to work with SDK 1.11.5?
- What changed in the image?
**Required**: Document in the PR descripti... | import asyncio
import os
from abc import ABC, abstractmethod
from openhands.agent_server import env_parser
from openhands.app_server.errors import SandboxError
from openhands.app_server.sandbox.sandbox_spec_models import (
SandboxSpecInfo,
SandboxSpecInfoPage,
)
from openhands.app_server.services.injector impo... | @@ -13,7 +13,7 @@
# The version of the agent server to use for deployments.
# Typically this will be the same as the values from the pyproject.toml
-AGENT_SERVER_IMAGE = 'ghcr.io/openhands/agent-server:61470a1-python'
+AGENT_SERVER_IMAGE = 'ghcr.io/openhands/agent-server:010e847-python' | openhands/app_server/sandbox/sandbox_spec_service.py | 16 | Python | 0.643 | suggestion | 401 | 41 | 41 | false | Bumped SDK to 1.11.5 | 13,002 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
) -> None:
"""React to an exception by setting the agent state to error and sending a status message."""
# Store the error reason before setting the agent state
self.state.last_error = f'{type(e).__name__}: {str(e)}'
if self.status_callback is not None:
runtime_status = ... | **question:** Could you please help clarify why this file needed to be modified? Is this file part of v0? Thank you! 🙏 | ) -> None:
"""React to an exception by setting the agent state to error and sending a status message."""
# Store the error reason before setting the agent state
self.state.last_error = f'{type(e).__name__}: {str(e)}'
if self.status_callback is not None:
runtime_status = ... | @@ -343,7 +343,9 @@ async def _react_to_exception(
elif isinstance(e, InternalServerError):
runtime_status = RuntimeStatus.ERROR_LLM_INTERNAL_SERVER_ERROR
self.state.last_error = runtime_status.value
- elif isinstance(e, BadRequestError) and 'ExceededBudget' in ... | openhands/controller/agent_controller.py | 26 | Python | 0.429 | suggestion | 119 | 51 | 51 | false | fix: detect team/org-level budget errors in error banner | 13,003 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | amanape |
) -> None:
"""React to an exception by setting the agent state to error and sending a status message."""
# Store the error reason before setting the agent state
self.state.last_error = f'{type(e).__name__}: {str(e)}'
if self.status_callback is not None:
runtime_status = ... | ```suggestion
elif isinstance(e, BadRequestError) and 'ExceededBudget' in str(e):
``` | ) -> None:
"""React to an exception by setting the agent state to error and sending a status message."""
# Store the error reason before setting the agent state
self.state.last_error = f'{type(e).__name__}: {str(e)}'
if self.status_callback is not None:
runtime_status = ... | @@ -343,7 +343,9 @@ async def _react_to_exception(
elif isinstance(e, InternalServerError):
runtime_status = RuntimeStatus.ERROR_LLM_INTERNAL_SERVER_ERROR
self.state.last_error = runtime_status.value
- elif isinstance(e, BadRequestError) and 'ExceededBudget' in ... | openhands/controller/agent_controller.py | 26 | Python | 0.714 | suggestion | 97 | 51 | 51 | false | fix: detect team/org-level budget errors in error banner | 13,003 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | amanape |
if key_id is None:
# Try to extract key_id from the token's header
try:
jwe_obj = jwcrypto_jwe.JWE()
jwe_obj.deserialize(token)
protected_header = json.loads(jwe_obj.objects['protected'])
key_id = protected_header.get('kid')... | 🔴 **CRITICAL - Data Structure**: You deserialize the token here to extract `kid`, then throw away the `jwe_obj` and deserialize it AGAIN on line 232. This is wasteful and shows you did not think about the data flow.
**Why it matters:** Deserialization is not free. You parse the JWE structure, base64-decode components... | # Deserialize once and reuse for both header extraction and decryption
try:
jwe_obj = jwcrypto_jwe.JWE()
jwe_obj.deserialize(token)
except Exception:
raise ValueError('Invalid JWE token format')
# Extract and validate the protected header
try:... | @@ -204,10 +204,14 @@ def decrypt_jwe_token(
if key_id is None:
# Try to extract key_id from the token's header
try:
- header = jwe.get_unverified_header(token)
- key_id = header.get('kid')
+ jwe_obj = jwcrypto_jwe.JWE()
+ jw... | openhands/app_server/services/jwt_service.py | 26 | Python | 1 | refactor | 974 | 51 | 51 | false | Fix CVE-2024-23342: Replace python-jose with jwcrypto | 13,012 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | aivong-openhands |
secret_key = self._keys[key_id].key.get_secret_value()
key_bytes = secret_key.encode() if isinstance(secret_key, str) else secret_key
# Derive a 256-bit key using SHA256
key_256 = hashlib.sha256(key_bytes).digest()
try:
# Create JWK from symmetric key for jwcrypto
... | 🟠 **Important - Simplification**: This entire block would disappear if you reuse the first `jwe_obj` instead of creating a new one. You are creating JWE objects like they are free. They are not.
See comment on line 217 for the fix. | raise ValueError('Unsupported or unexpected JWE algorithm')
if key_id is None:
# Extract key_id from the token's header
key_id = protected_header.get('kid')
if not key_id:
raise ValueError("Token does not contain 'kid' header with key ID")
... | @@ -221,10 +225,16 @@ def decrypt_jwe_token(
key_256 = hashlib.sha256(key_bytes).digest()
try:
- payload_json = jwe.decrypt(token, key_256)
- assert payload_json is not None
+ # Create JWK from symmetric key for jwcrypto
+ symmetric_key = jwk.JWK(kty='oct'... | openhands/app_server/services/jwt_service.py | 26 | Python | 0.643 | suggestion | 232 | 38 | 48 | false | Fix CVE-2024-23342: Replace python-jose with jwcrypto | 13,012 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | aivong-openhands |
"""Decrypt and decode a JWE token.
Args:
token: The JWE token to decrypt
key_id: The key ID to use for decryption. If None, extracts
from token header.
Returns:
The decrypted JWT payload
Raises:
ValueError: If token i... | 🟡 **Suggestion - Error Handling**: The pattern `except ValueError: raise` followed by `except Exception: raise ValueError(...)` is unusual. You are catching ValueError to preserve the specific message, then converting everything else to a generic message.
This works but is subtle. Consider being explicit:
```python
... | """Decrypt and decode a JWE token.
Args:
token: The JWE token to decrypt
key_id: The key ID to use for decryption. If None, extracts
from token header.
Returns:
The decrypted JWT payload
Raises:
ValueError: If token i... | @@ -204,10 +204,14 @@ def decrypt_jwe_token(
if key_id is None:
# Try to extract key_id from the token's header
try:
- header = jwe.get_unverified_header(token)
- key_id = header.get('kid')
+ jwe_obj = jwcrypto_jwe.JWE()
+ jw... | openhands/app_server/services/jwt_service.py | 26 | Python | 1 | suggestion | 713 | 51 | 51 | false | Fix CVE-2024-23342: Replace python-jose with jwcrypto | 13,012 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | aivong-openhands |
Args:
token: The JWE token to decrypt
key_id: The key ID to use for decryption. If None, extracts
from token header.
Returns:
The decrypted JWT payload
Raises:
ValueError: If token is invalid or key_id is not found
... | 🟠 **Important - Security (Defense-in-Depth)**: Missing algorithm verification. Before using this token, verify the algorithms match expectations:
```python
if protected_header.get('alg') != 'dir' or protected_header.get('enc') != 'A256GCM':
raise ValueError("Unsupported or unexpected JWE algorithm")
```
**Why it... | Args:
token: The JWE token to decrypt
key_id: The key ID to use for decryption. If None, extracts
from token header.
Returns:
The decrypted JWT payload
Raises:
ValueError: If token is invalid or key_id is not found
... | @@ -201,15 +201,22 @@ def decrypt_jwe_token(
ValueError: If token is invalid or key_id is not found
Exception: If token decryption fails
"""
+ # Deserialize once and reuse for both header extraction and decryption
+ try:
+ jwe_obj = jwcrypto_jwe.JWE()
+ ... | openhands/app_server/services/jwt_service.py | 26 | Python | 1 | bug | 826 | 51 | 51 | false | Fix CVE-2024-23342: Replace python-jose with jwcrypto | 13,012 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | aivong-openhands |
token: The JWE token to decrypt
key_id: The key ID to use for decryption. If None, extracts
from token header.
Returns:
The decrypted JWT payload
Raises:
ValueError: If token is invalid or key_id is not found
Exception: If... | 🟡 **Suggestion - Error Handling**: The error message pattern `f'Invalid JWE token format: {type(e).__name__}'` produces output like "Invalid JWE token format: KeyError".
This is neither fully helpful (doesn't say *which* key) nor fully generic. Either commit to one style:
- Generic: `raise ValueError('Invalid JWE tok... | token: The JWE token to decrypt
key_id: The key ID to use for decryption. If None, extracts
from token header.
Returns:
The decrypted JWT payload
Raises:
ValueError: If token is invalid or key_id is not found
Exception: If... | @@ -201,15 +201,22 @@ def decrypt_jwe_token(
ValueError: If token is invalid or key_id is not found
Exception: If token decryption fails
"""
+ # Deserialize once and reuse for both header extraction and decryption
+ try:
+ jwe_obj = jwcrypto_jwe.JWE()
+ ... | openhands/app_server/services/jwt_service.py | 26 | Python | 0.786 | bug | 517 | 51 | 51 | false | Fix CVE-2024-23342: Replace python-jose with jwcrypto | 13,012 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | aivong-openhands |
"""Legacy method to get sandbox by session API key via runtime API.
This is the fallback for sandboxes created before the session_api_key_hash
column was added. It calls the remote runtime API which is less efficient.
"""
try:
response = await self._send_runtime_api_... | 🟡 Suggestion: The backfilling here modifies `sandbox.session_api_key_hash` but doesn't explicitly commit to the database. This relies on SQLAlchemy's session management flushing the change at the right time. Consider adding a comment explaining this implicit commit behavior, or explicitly calling `await self.db_sessio... | """Legacy method to get sandbox by session API key via runtime API.
This is the fallback for sandboxes created before the session_api_key_hash
column was added. It calls the remote runtime API which is less efficient.
"""
try:
response = await self._send_runtime_api_... | @@ -366,6 +375,10 @@ async def get_sandbox_by_session_api_key(
sandbox = result.scalar_one_or_none()
if sandbox is None:
raise ValueError('sandbox_not_found')
+ # Backfill the hash for future lookups
+ sandbox.sessi... | openhands/app_server/sandbox/remote_sandbox_service.py | 26 | Python | 0.643 | suggestion | 343 | 51 | 51 | false | Optimize get_sandbox_by_session_api_key with hash lookup | 13,019 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
)
# Get all stored sandboxes for the current user
stmt = await self._secure_select()
result = await self.db_session.execute(stmt)
stored_sandboxes = result.scalars().all()
# Check each sandbox's runtime data for matching session_api_key
for stored_sandbox in... | 🟡 Suggestion: Similar implicit commit issue as above. The hash is backfilled but not explicitly persisted. While SQLAlchemy likely handles this, explicit persistence would make the code clearer and ensure the optimization works on subsequent lookups. | )
# Get all stored sandboxes for the current user
stmt = await self._secure_select()
result = await self.db_session.execute(stmt)
stored_sandboxes = result.scalars().all()
# Check each sandbox's runtime data for matching session_api_key
for stored_sandbox in... | @@ -382,13 +395,50 @@ async def get_sandbox_by_session_api_key(
try:
runtime = await self._get_runtime(stored_sandbox.id)
if runtime and runtime.get('session_api_key') == session_api_key:
+ # Backfill the hash for future lookups
+ stor... | openhands/app_server/sandbox/remote_sandbox_service.py | 26 | Python | 0.571 | suggestion | 250 | 51 | 51 | false | Optimize get_sandbox_by_session_api_key with hash lookup | 13,019 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
LOG_DIR = os.path.join(
# parent dir of openhands/core (i.e., root of the repo)
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
'logs',
)
if LOG_TO_FILE:
openhands_logger.addHandler(
get_file_handler(LOG_DIR, current_log_level)
) # default log to project root
... | 🟠 Important: Your PR description says "error logs" but this sets level to WARNING, which only suppresses INFO/DEBUG. If Alembic is actually logging at ERROR level, this change does nothing. If they're INFO/DEBUG logs, the terminology is misleading.
**Question**: What log level are these messages actually at? Did you ... | LOG_DIR = os.path.join(
# parent dir of openhands/core (i.e., root of the repo)
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
'logs',
)
if LOG_TO_FILE:
openhands_logger.addHandler(
get_file_handler(LOG_DIR, current_log_level)
) # default log to project root
... | @@ -431,6 +431,7 @@ def log_uncaught_exceptions(
'socketio.client',
'socketio.server',
'aiosqlite',
+ 'alembic.runtime.plugins', | openhands/core/logger.py | 26 | Python | 0.643 | bug | 363 | 51 | 51 | false | Make logs quieter. | 13,042 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
# parent dir of openhands/core (i.e., root of the repo)
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
'logs',
)
if LOG_TO_FILE:
openhands_logger.addHandler(
get_file_handler(LOG_DIR, current_log_level)
) # default log to project root
openhands_logger.deb... | 🟡 Suggestion: Python logging is hierarchical. Since `alembic.runtime.plugins` is the parent of `alembic.runtime.plugins.setup`, setting the parent to WARNING should automatically apply to the child. Having both entries is likely redundant unless the child explicitly overrides its level elsewhere (unlikely).
Test remo... | # parent dir of openhands/core (i.e., root of the repo)
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
'logs',
)
if LOG_TO_FILE:
openhands_logger.addHandler(
get_file_handler(LOG_DIR, current_log_level)
) # default log to project root
openhands_logger.deb... | @@ -431,6 +431,7 @@ def log_uncaught_exceptions(
'socketio.client',
'socketio.server',
'aiosqlite',
+ 'alembic.runtime.plugins',
'alembic.runtime.plugins.setup', | openhands/core/logger.py | 26 | Python | 0.643 | suggestion | 362 | 51 | 51 | false | Make logs quieter. | 13,042 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
# parent dir of openhands/core (i.e., root of the repo)
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
'logs',
)
if LOG_TO_FILE:
openhands_logger.addHandler(
get_file_handler(LOG_DIR, current_log_level)
) # default log to project root
openhands_logger.deb... | 🟠 Important: **Root Cause Missing** - Why is Alembic spamming logs in the first place?
You're treating symptoms, not the disease. Legitimate questions:
1. Is there a misconfigured migration setup?
2. Are these warnings about actual problems we should fix?
3. Should Alembic's own logging config be adjusted instead?
S... | # parent dir of openhands/core (i.e., root of the repo)
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
'logs',
)
if LOG_TO_FILE:
openhands_logger.addHandler(
get_file_handler(LOG_DIR, current_log_level)
) # default log to project root
openhands_logger.deb... | @@ -431,6 +431,7 @@ def log_uncaught_exceptions(
'socketio.client',
'socketio.server',
'aiosqlite',
+ 'alembic.runtime.plugins',
'alembic.runtime.plugins.setup', | openhands/core/logger.py | 26 | Python | 0.643 | bug | 498 | 51 | 51 | false | Make logs quieter. | 13,042 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { organizationService } from "#/api/organization-service/organization-service.api";
import { useSelectedOrganizationId } from "#/context/use-selected-organization";
export const useDeleteOrganization... | 🟡 Suggestion: **Incomplete Cache Cleanup** - Are there other org-related queries that should be cleared? For example, org members, org settings, org permissions, etc. If those queries still exist in cache after deletion, they might cause similar issues.
Consider auditing all query keys that include the organizationId... | import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { organizationService } from "#/api/organization-service/organization-service.api";
import { useSelectedOrganizationId } from "#/context/use-selected-organization";
export const useDeleteOrganization... | @@ -14,11 +14,22 @@ export const useDeleteOrganization = () => {
return organizationService.deleteOrganization({ orgId: organizationId });
},
onSuccess: () => {
- setOrganizationId(null);
- queryClient.invalidateQueries({
+ // Remove stale cache BEFORE clearing the selected organization.... | frontend/src/hooks/mutation/use-delete-organization.ts | 25 | TypeScript | 0.5 | security | 343 | 26 | 37 | false | fix(frontend): resolve 403 error after organization deletion caused by stale cache race condition | 13,061 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { organizationService } from "#/api/organization-service/organization-service.api";
import { useSelectedOrganizationId } from "#/context/use-selected-organization";
export const useDeleteOrganization... | 🟡 Suggestion: **Inconsistent `exact` Flag** - The first `removeQueries` has `exact: true` but the second doesn't. Is this intentional?
If the second call is meant to remove all queries starting with `["organizations", organizationId]` (e.g., `["organizations", "123", "members"]`), this is fine, but the reasoning shou... | import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { organizationService } from "#/api/organization-service/organization-service.api";
import { useSelectedOrganizationId } from "#/context/use-selected-organization";
export const useDeleteOrganization... | @@ -14,11 +14,22 @@ export const useDeleteOrganization = () => {
return organizationService.deleteOrganization({ orgId: organizationId });
},
onSuccess: () => {
- setOrganizationId(null);
- queryClient.invalidateQueries({
+ // Remove stale cache BEFORE clearing the selected organization.... | frontend/src/hooks/mutation/use-delete-organization.ts | 22 | TypeScript | 0.643 | suggestion | 404 | 26 | 37 | false | fix(frontend): resolve 403 error after organization deletion caused by stale cache race condition | 13,061 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { organizationService } from "#/api/organization-service/organization-service.api";
import { useSelectedOrganizationId } from "#/context/use-selected-organization";
export const useDeleteOrganization... | 🟢 Good: **Comments Justify Complexity** - These comments explain the race condition and ordering requirement clearly. For timing-sensitive code like this, explicit documentation of the "why" is valuable. This is one of the rare cases where verbose comments add real value. | import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { organizationService } from "#/api/organization-service/organization-service.api";
import { useSelectedOrganizationId } from "#/context/use-selected-organization";
export const useDeleteOrganization... | @@ -14,11 +14,22 @@ export const useDeleteOrganization = () => {
return organizationService.deleteOrganization({ orgId: organizationId });
},
onSuccess: () => {
- setOrganizationId(null);
- queryClient.invalidateQueries({
+ // Remove stale cache BEFORE clearing the selected organization.... | frontend/src/hooks/mutation/use-delete-organization.ts | 26 | TypeScript | 0.571 | bug | 272 | 26 | 37 | false | fix(frontend): resolve 403 error after organization deletion caused by stale cache race condition | 13,061 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
logger.warning('auth_error', exc_info=True)
try:
await self._logout(request)
except Exception as logout_error:
logger.debug(str(logout_error))
# Send a response that deletes the auth cookie if needed
response = JSONResponse(
... | 🟠 **Important - Security Logic**: You check if `api_auth_header` exists but never validate its value in this code path. The header presence check without validation provides no actual security. Either validate the token here or document why existence alone is sufficient. | logger.warning('auth_error', exc_info=True)
try:
await self._logout(request)
except Exception as logout_error:
logger.debug(str(logout_error))
# Send a response that deletes the auth cookie if needed
response = JSONResponse(
... | @@ -103,11 +103,13 @@ def _check_tos(self, request: Request):
keycloak_auth_cookie = request.cookies.get('keycloak_auth')
auth_header = request.headers.get('Authorization')
mcp_auth_header = request.headers.get('X-Session-API-Key')
+ api_auth_header = request.headers.get('X-Access-Toke... | enterprise/server/middleware.py | 26 | Python | 0.714 | security | 271 | 51 | 51 | false | Fix api key access | 13,064 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
# 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 ser... | 🟡 **Design - Ceremony for Documentation**: Creating a non-validating dependency (`auto_error=False`) just to populate OpenAPI docs is a code smell. FastAPI has proper ways to document security requirements using `security_schemes` in OpenAPI config without fake dependencies. This approach adds complexity without actua... |
from openhands.app_server.config import get_global_config
from openhands.server.types import AppMode
_SESSION_API_KEY = os.getenv('SESSION_API_KEY')
_SESSION_API_KEY_HEADER = APIKeyHeader(name='X-Session-API-Key', auto_error=False)
def check_session_api_key(
session_api_key: str | None = Depends(_SESSION_API_KE... | @@ -29,4 +32,9 @@ def get_dependencies() -> list[Depends]:
result = []
if _SESSION_API_KEY:
result.append(Depends(check_session_api_key))
+ elif get_global_config().app_mode == AppMode.SAAS:
+ # This merely lets the OpenAPI Docs know that an X-Session-API-Key can be
+ # used for secu... | openhands/server/dependencies.py | 26 | Python | 0.786 | security | 459 | 33 | 29 | false | Fix api key access | 13,064 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
from openhands.storage.data_models.secrets import Secrets
from openhands.storage.secrets.secrets_store import SecretsStore
from openhands.storage.settings.settings_store import SettingsStore
async def get_provider_tokens(request: Request) -> PROVIDER_TOKEN_TYPE | None:
user_auth = await get_user_auth(request)
... | 🔴 **Critical - Unused Parameter**: The `api_key_header` parameter is never used in the function body - its pure ceremony for OpenAPI docs. This violates good taste: if youre adding parameters just for documentation side-effects, your architecture needs rethinking.
**Why this is bad:**
1. Anyone reading this function ... | from openhands.server.user_auth.user_auth import AuthType, get_user_auth
from openhands.storage.data_models.secrets import Secrets
from openhands.storage.secrets.secrets_store import SecretsStore
from openhands.storage.settings.settings_store import SettingsStore
async def get_provider_tokens(request: Request) -> PRO... | @@ -21,7 +22,15 @@ async def get_access_token(request: Request) -> SecretStr | None:
return access_token
-async def get_user_id(request: Request) -> str | None:
+async def get_user_id(
+ request: Request,
+ api_key_header: str | None = Depends(
+ APIKeyHeader(name='X-Access-Token', auto_error=Fals... | openhands/server/user_auth/__init__.py | 26 | Python | 0.786 | security | 634 | 51 | 51 | false | Fix api key access | 13,064 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
depends_app_conversation_service,
depends_app_conversation_start_task_service,
depends_db_session,
depends_httpx_client,
depends_sandbox_service,
depends_sandbox_spec_service,
depends_user_context,
get_app_conversation_service,
)
from openhands.app_server.sandbox.sandbox_models import (
... | 🟡 **Pattern - Architecture Smell**: This comment pattern appears across multiple routers: "We use get_dependencies method here to signal to the OpenAPI docs that this endpoint is protected. The actual protection is provided by SetAuthCookieMiddleware."
When you need comments explaining that code exists only for side-... | from openhands.app_server.config import (
depends_app_conversation_service,
depends_app_conversation_start_task_service,
depends_db_session,
depends_httpx_client,
depends_sandbox_service,
depends_sandbox_spec_service,
depends_user_context,
get_app_conversation_service,
)
from openhands.a... | @@ -74,7 +75,11 @@ async def anext(async_iterator):
from openhands.sdk.context.skills import KeywordTrigger, TaskTrigger
from openhands.sdk.workspace.remote.async_remote_workspace import AsyncRemoteWorkspace
-router = APIRouter(prefix='/app-conversations', tags=['Conversations'])
+# We use the get_dependencies meth... | openhands/app_server/app_conversation/app_conversation_router.py | 26 | Python | 0.5 | bug | 449 | 51 | 51 | false | Fix api key access | 13,064 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.future import select
from storage.database import session_maker
from storage.feedback import ConversationFeedback
from storage.stored_conversation_metadata_sa... | 🟠 **Important - Potential Bug**: The TODO comment raises a real concern: "you can actually post feedback to a conversation you dont own right now." If this is a real security issue, it shouldnt be left as a TODO in a PR that claims to fix authentication. Either fix it or file a separate issue, but dont hand-wave secur... | from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.future import select
from storage.database import session_maker
from storage.feedback import ConversationFeedback
from storage.stored_conversation_metadata_sa... | @@ -8,11 +8,18 @@
from storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas
from openhands.events.event_store import EventStore
+from openhands.server.dependencies import get_dependencies
from openhands.server.shared import file_store
from openhands.server.user_auth import get_user_id
... | enterprise/server/routes/feedback.py | 17 | Python | 0.643 | bug | 332 | 42 | 42 | false | Fix api key access | 13,064 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
},
{ onSettled: () => setMemberToUpdateRole(null) },
);
}
};
const handleRemoveMember = (member: OrganizationMember) => {
setMemberToRemove(member);
};
const handleConfirmRemoveMember = () => {
if (memberToRemove) {
removeMember(
{ userId: memberToRemove.user_id... | 🟢 **Good Taste**: Removing `user?.role !== member.role` is the right move. This eliminates a special case and properly delegates the permission check to `hasPermission()`. The backend should be the source of truth for who can edit whom, not the frontend. | },
{ onSettled: () => setMemberToUpdateRole(null) },
);
}
};
const handleRemoveMember = (member: OrganizationMember) => {
setMemberToRemove(member);
};
const handleConfirmRemoveMember = () => {
if (memberToRemove) {
removeMember(
{ userId: memberToRemove.user_id... | @@ -125,7 +125,6 @@ function ManageOrganizationMembers() {
const canAssignUserRole = (member: OrganizationMember) =>
user != null &&
user?.user_id !== member.user_id && | frontend/src/routes/manage-organization-members.tsx | 26 | TypeScript | 0.643 | security | 254 | 51 | 51 | false | feat(frontend): allow owners to edit owners and admins to edit admins (org project) | 13,087 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
expect(removeMemberSpy).toHaveBeenCalledExactlyOnceWith({
orgId: "2",
userId: "3",
});
// Verify the user is no longer in the list
await waitFor(() => {
const updatedMemberListItems = screen.getAllByTestId("member-item");
expect(updatedMemberListItems).toHaveLength(initialMembe... | 🟡 **Testing Strategy**: These tests heavily mock backend responses (getOrganizationMembers, getOrganizationMembersCount, etc.), which is acceptable for frontend unit tests. However, ensure that:
1. Integration tests exist that verify the actual backend permission logic (`_can_update_member_role`, `_can_remove_member`... | llm_api_key: "**********",
max_iterations: 20,
llm_model: "gpt-4",
llm_api_key_for_byor: null,
llm_base_url: "https://api.openai.com",
status: "active",
});
const updateMemberRoleSpy = createUpdateMemberRoleSpy();
renderManageOrganizationMembers();
await screen.find... | @@ -415,45 +415,124 @@ describe("Manage Organization Members Route", () => {
});
it("should not allow an admin to change the owner's role", async () => {
- await verifyRoleChangeNotPermitted(
+ // User is bob (admin, user_id: "2") trying to edit alice (owner, user_id: "1")
+ // Admins don't have change... | frontend/__tests__/routes/manage-organization-members.test.tsx | 26 | TypeScript | 0.786 | bug | 542 | 51 | 51 | false | feat(frontend): allow owners to edit owners and admins to edit admins (org project) | 13,087 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
expect(updateMemberRoleSpy).toHaveBeenCalledExactlyOnceWith({
userId: "3", // charlie's id
orgId: "2",
role: "admin",
});
expectDropdownNotVisible(userRoleMember);
// Verify the role has been updated in the UI
userCombobox = within(userRoleMember).getByText(/^Admin$/i);
expec... | 🟠 **Critical**: The PR description mentions backend changes to `enterprise/server/services/org_member_service.py` (specifically `_can_update_member_role` and `_can_remove_member`), but these changes are not included in this diff.
**This is a blocker for proper review**. I cannot verify that:
- Owners can actually mo... |
expect(updateMemberRoleSpy).toHaveBeenCalledExactlyOnceWith({
userId: "3", // charlie's id
orgId: "2",
role: "admin",
});
expectDropdownNotVisible(userRoleMember);
// Verify the role has been updated in the UI
userCombobox = within(userRoleMember).getByText(/^Admin$/i);
expec... | @@ -415,45 +415,124 @@ describe("Manage Organization Members Route", () => {
});
| frontend/__tests__/routes/manage-organization-members.test.tsx | 26 | TypeScript | 0.643 | bug | 663 | 51 | 51 | false | feat(frontend): allow owners to edit owners and admins to edit admins (org project) | 13,087 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
platform: The platform on which the image should be built. Default is None.
remote_runtime_resource_factor: Factor to scale the resource allocation for remote runtime.
Must be one of [1, 2, 4, 8]. Will only be used if the runtime is remote.
enable_gpu: Whether to enable GPU.
... | No issues found. | platform: The platform on which the image should be built. Default is None.
remote_runtime_resource_factor: Factor to scale the resource allocation for remote runtime.
Must be one of [1, 2, 4, 8]. Will only be used if the runtime is remote.
enable_gpu: Whether to enable GPU.
... | @@ -18,6 +18,7 @@ class SandboxConfig(BaseModel):
remote_runtime_enable_retries: Whether to enable retries (on recoverable errors like requests.ConnectionError) for the remote runtime API requests.
enable_auto_lint: Whether to enable auto-lint.
use_host_network: Whether to use the host networ... | openhands/core/config/sandbox_config.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add additional networks | 9,566 | All-Hands-AI/OpenHands | 55,974 | Python | Joeoc2001 | |
"""
Test that Gemini 2.5 Pro models have function calling enabled by default.
This includes testing various model name formats with different prefixes.
"""
# Mock the model info response
mock_get_model_info.return_value = {
'max_input_tokens': 8000,
'max_output_tokens': 2000,
... | No issues found. | """
Test that Gemini 2.5 Pro models have function calling enabled by default.
This includes testing various model name formats with different prefixes.
"""
# Mock the model info response
mock_get_model_info.return_value = {
'max_input_tokens': 8000,
'max_output_tokens': 2000,
... | @@ -264,6 +264,45 @@ def test_llm_init_with_openrouter_model(mock_get_model_info, default_config):
mock_get_model_info.assert_called_once_with('openrouter:gpt-4o-mini')
+@patch('openhands.llm.llm.litellm_completion')
+def test_stop_parameter_handling(mock_litellm_completion, default_config):
+ """Test that ... | tests/unit/test_llm.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix issue #9655: [Bug]: CodeActAgent is incompatible with xAI Grok-4 due to hardcoded stop parameter | 9,666 | All-Hands-AI/OpenHands | 55,974 | Python | openhands-agent | |
if sys.platform == 'win32':
logger.debug('Running on Windows, skipping Unix-specific user setup')
logger.debug(f'Client working directory: {initial_cwd}')
# Create the working directory if it doesn't exist
os.makedirs(initial_cwd, exist_ok=True)
logger.debug(f'Created workin... | No issues found. | if sys.platform == 'win32':
logger.debug('Running on Windows, skipping Unix-specific user setup')
logger.debug(f'Client working directory: {initial_cwd}')
# Create the working directory if it doesn't exist
os.makedirs(initial_cwd, exist_ok=True)
logger.debug(f'Created workin... | @@ -49,6 +49,61 @@ def init_user_and_working_directory(
if username == os.getenv('USER') and username not in ['root', 'openhands']:
return None
+ # Skip root since it is already created
+ if username != 'root':
+ # Check if the username already exists
+ logger.debug(f'Attempting to c... | openhands/runtime/utils/runtime_init.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Non root user | 10,155 | All-Hands-AI/OpenHands | 55,974 | Python | chuckbutkus | |
1, per_page, sort, workspace_slug, query
)
repositories.extend(repos)
except Exception:
continue
return repositories
async def _get_user_workspaces(self) -> list[dict[str, Any]]:
"""Get all workspaces the user has acce... | No issues found. | 1, per_page, sort, workspace_slug, query
)
repositories.extend(repos)
except Exception:
continue
return repositories
async def _get_user_workspaces(self) -> list[dict[str, Any]]:
"""Get all workspaces the user has acce... | @@ -65,6 +65,24 @@ def __init__(
def provider(self) -> str:
return ProviderType.BITBUCKET.value
+ def _extract_owner_and_repo(self, repository: str) -> tuple[str, str]:
+ """Extract owner and repo from repository string.
+
+ Args:
+ repository: Repository name in format 'work... | openhands/integrations/bitbucket/bitbucket_service.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | fix(backend): show name of created branch in conversation list. | 10,208 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
Component: () => <TaskSuggestions />,
path: "/",
},
{
Component: () => <div data-testid="conversation-screen" />,
path: "/conversations/:conversationId",
},
{
Component: () => <div data-testid="settings-screen" />,
path: "/settings",
},
]);
return render(<Rou... | No issues found. | Component: () => <TaskSuggestions />,
path: "/",
},
{
Component: () => <div data-testid="conversation-screen" />,
path: "/conversations/:conversationId",
},
{
Component: () => <div data-testid="settings-screen" />,
path: "/settings",
},
]);
return render(<Rou... | @@ -22,6 +22,14 @@ vi.mock("react-i18next", async () => {
};
});
+// Mock the useIsAuthed hook to return authenticated
+vi.mock("#/hooks/query/use-is-authed", () => ({
+ useIsAuthed: () => ({
+ data: true,
+ isLoading: false,
+ }),
+}));
+
const renderTaskSuggestions = () => {
const RouterStub = creat... | frontend/__tests__/components/features/home/task-suggestions.test.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): update the styling for suggested tasks. | 10,322 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
? searchData.map((repo) => ({
value: repo.id,
label: repo.full_name,
}))
: [],
[searchData],
);
const selectedOption = useMemo(() => {
// First check in loaded pages
const option = allOptions.find((opt) => opt.value === value);
if (option) return op... | No issues found. | ? searchData.map((repo) => ({
value: repo.id,
label: repo.full_name,
}))
: [],
[searchData],
);
const selectedOption = useMemo(() => {
// First check in loaded pages
const option = allOptions.find((opt) => opt.value === value);
if (option) return op... | @@ -1,7 +1,9 @@
-import { useCallback, useMemo, useRef } from "react";
+import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Provider } from "../../types/settings";
import { useGitRepositories } from "../../hooks/query/use-git-repositories";
+import { useSe... | frontend/src/components/common/git-repository-dropdown.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix: Enhance GitHub repository search to include user organizations | 10,324 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | |
"""Test that very long conversation IDs are rejected with 400 Bad Request.
This is the main test case for GitHub issue #10489.
"""
# Test with 1000 character ID (similar to the reported issue)
long_id = 'a' * 1000
with pytest.raises(HTTPException) as exc_info:
... | No issues found. | """Test that very long conversation IDs are rejected with 400 Bad Request.
This is the main test case for GitHub issue #10489.
"""
# Test with 1000 character ID (similar to the reported issue)
long_id = 'a' * 1000
with pytest.raises(HTTPException) as exc_info:
... | @@ -0,0 +1,118 @@
+"""
+Test cases for conversation ID validation to ensure proper error handling.
+
+This addresses GitHub issue #10489 where long conversation IDs were returning
+500 Internal Server Error instead of proper 4xx errors.
+"""
+
+import pytest
+from fastapi import HTTPException, status
+
+from openhands.... | tests/unit/server/routes/test_conversation_id_validation.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix conversation ID validation to return 400 instead of 500 for long IDs | 10,496 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | |
const maxScrollLeft = container.scrollWidth - container.clientWidth;
return Math.min(maxScrollLeft, container.scrollLeft + scrollAmount);
};
// Calculate scroll amount based on wheel delta
const calculateWheelScrollAmount = (deltaY: number): number =>
// Use a smaller multiplier for more controlled s... | No issues found. | const maxScrollLeft = container.scrollWidth - container.clientWidth;
return Math.min(maxScrollLeft, container.scrollLeft + scrollAmount);
};
// Calculate scroll amount based on wheel delta
const calculateWheelScrollAmount = (deltaY: number): number =>
// Use a smaller multiplier for more controlled s... | @@ -0,0 +1,174 @@
+import { useRef, useState, useEffect } from "react";
+
+interface UseHorizontalScrollOptions {
+ scrollAmount?: number;
+ scrollBehavior?: ScrollBehavior;
+}
+
+interface UseHorizontalScrollReturn {
+ scrollContainerRef: React.RefObject<HTMLDivElement | null>;
+ canScrollLeft: boolean;
+ canScro... | frontend/src/hooks/use-horizontal-scroll.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(frontend): add the scroll buttons to scroll the git control bar | 10,498 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
from openhands.core.config.toml_writer import TOMLConfigWriter
from openhands.core.config.utils import load_from_toml
def test_roundtrip_mixed_sections(tmp_path: Path):
cfg_path = tmp_path / 'config.toml'
# 1) Write a complex configuration
writer = TOMLConfigWriter(str(cfg_path))
# core values
w... | No issues found. | from openhands.core.config.toml_writer import TOMLConfigWriter
from openhands.core.config.utils import load_from_toml
def test_roundtrip_mixed_sections(tmp_path: Path):
cfg_path = tmp_path / 'config.toml'
# 1) Write a complex configuration
writer = TOMLConfigWriter(str(cfg_path))
# core values
w... | @@ -0,0 +1,72 @@
+from pathlib import Path
+
+from openhands.core.config.agent_config import AgentConfig
+from openhands.core.config.condenser_config import LLMSummarizingCondenserConfig
+from openhands.core.config.kubernetes_config import KubernetesConfig
+from openhands.core.config.llm_config import LLMConfig
+from o... | tests/unit/config/test_toml_writer_roundtrip.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | feat(config-writer): tomlkit-based writer with comment preservation, explicit APIs, atomic writes + add tomlkit dep | 10,512 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | |
number
title
repository {
nameWithOwner
}
}
}
}
}
"""
get_thread_from_comment_graphql_query = """
query GetThreadFromComment($commentId: ID!) {
node(id: $commentId) {
... on PullRequestReviewComm... | No issues found. | number
title
repository {
nameWithOwner
}
}
}
}
}
"""
get_thread_from_comment_graphql_query = """
query GetThreadFromComment($commentId: ID!) {
node(id: $commentId) {
... on PullRequestReviewComm... | @@ -45,3 +45,80 @@
}
}
"""
+
+get_thread_from_comment_graphql_query = """
+ query GetThreadFromComment($commentId: ID!) {
+ node(id: $commentId) {
+ ... on PullRequestReviewComment {
+ id
+ body
+ author {
+ login
+ ... | openhands/integrations/github/queries.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | [Bug, GitHub]: fix missing context in cloud resolver | 10,517 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
assert isinstance(agent, KnowledgeMicroagent)
assert agent.name == 'test_agent'
assert agent.metadata.version == '2512312' # Should be converted to string
assert isinstance(agent.metadata.version, str) # Ensure it's actually a string
assert agent.type == MicroagentType.KNOWLEDGE
def test_microag... | No issues found. | assert isinstance(agent, KnowledgeMicroagent)
assert agent.name == 'test_agent'
assert agent.metadata.version == '2512312' # Should be converted to string
assert isinstance(agent.metadata.version, str) # Ensure it's actually a string
assert agent.type == MicroagentType.KNOWLEDGE
def test_microag... | @@ -364,3 +364,184 @@ def test_load_microagents_with_cursorrules(temp_microagents_dir_with_cursorrules
assert cursorrules_agent.name == 'cursorrules'
assert 'Always use TypeScript for new files' in cursorrules_agent.content
assert cursorrules_agent.type == MicroagentType.REPO_KNOWLEDGE
+
+
+@pytest.fixtu... | tests/unit/microagent/test_microagent_utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add support for AGENTS.md files in microagent system | 10,528 | All-Hands-AI/OpenHands | 55,974 | Python | ryanhoangt | |
return (
<ContextMenu
ref={ref}
testId="context-menu"
position={position}
alignment="right"
size="compact"
className="p-1"
>
{generateSection([
onEdit && (
<ContextMenuListItem
testId="edit-button"
onClick={onEdit}
... | No issues found. | return (
<ContextMenu
ref={ref}
testId="context-menu"
position={position}
alignment="right"
size="compact"
className="p-1"
>
{generateSection([
onEdit && (
<ContextMenuListItem
testId="edit-button"
onClick={onEdit}
... | @@ -1,8 +1,7 @@
-import { useTranslation } from "react-i18next";
import React, { useCallback } from "react";
+import { useTranslation } from "react-i18next";
import { useClickOutsideElement } from "#/hooks/use-click-outside-element";
-import { cn } from "#/utils/utils";
-import { ContextMenu } from "../../context-men... | frontend/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): context menu into a reusable component | 10,546 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
self.config.mcp.shttp_servers.append(openhands_mcp_server)
self.logger.debug('Added default MCP HTTP server to config')
self.config.mcp.stdio_servers.extend(openhands_mcp_stdio_servers)
self.logger.debug(
f'MCP configuration after setup - self.config.mcp: {self.... | No issues found. | self.config.mcp.shttp_servers.append(openhands_mcp_server)
self.logger.debug('Added default MCP HTTP server to config')
self.config.mcp.stdio_servers.extend(openhands_mcp_stdio_servers)
self.logger.debug(
f'MCP configuration after setup - self.config.mcp: {self.... | @@ -37,7 +37,28 @@
from openhands.storage.files import FileStore
-class Session:
+class WebSession:
+ """Web server-bound session wrapper.
+
+ This was previously named `Session`. We keep `Session` as a compatibility alias
+ (see openhands.server.session.__init__) so downstream imports/tests continue to
+... | openhands/server/session/session.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | chore(server): rename Session to WebSession | 10,565 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | |
m for m in provider_models if m not in VERIFIED_OPENAI_MODELS
]
provider_models = VERIFIED_OPENAI_MODELS + provider_models
if provider == 'anthropic':
provider_models = [
m for m in provider_models if m not in VERIFIED_ANTHROPIC_MODELS
... | No issues found. | m for m in provider_models if m not in VERIFIED_OPENAI_MODELS
]
provider_models = VERIFIED_OPENAI_MODELS + provider_models
if provider == 'anthropic':
provider_models = [
m for m in provider_models if m not in VERIFIED_ANTHROPIC_MODELS
... | @@ -479,11 +479,10 @@ def model_validator(x):
settings = Settings()
settings.llm_model = f'{provider}{organized_models[provider]["separator"]}{model}'
- settings.llm_api_key = SecretStr(api_key)
+ settings.llm_api_key = SecretStr(api_key) if api_key and api_key.strip() else None
settings.llm_... | openhands/cli/settings.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | fix: resolve empty API keys to None and add Bedrock model support | 10,573 | All-Hands-AI/OpenHands | 55,974 | Python | JAxeAddepar | |
export type ConversationStatus =
| "STARTING"
| "RUNNING"
| "STOPPED"
| "ARCHIVED"
| "ERROR";
| No issues found. | export type ConversationStatus =
| "STARTING"
| "RUNNING"
| "STOPPED"
| "ARCHIVED"
| "ERROR";
| @@ -1 +1,6 @@
-export type ConversationStatus = "STARTING" | "RUNNING" | "STOPPED";
+export type ConversationStatus =
+ | "STARTING"
+ | "RUNNING"
+ | "STOPPED"
+ | "ARCHIVED"
+ | "ERROR"; | frontend/src/types/conversation-status.ts | 0 | TypeScript | 1 | none | 16 | 7 | 7 | true | Refactor conversation status | 10,590 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | |
custom_host_exists or default_host_exists
)
def _deduplicate_repositories(self, repos: list[Repository]) -> list[Repository]:
"""Remove duplicate repositories based on full_name."""
seen = set()
unique_repos = []
for repo in repos:
if repo.full_name n... | No issues found. | custom_host_exists or default_host_exists
)
def _deduplicate_repositories(self, repos: list[Repository]) -> list[Repository]:
"""Remove duplicate repositories based on full_name."""
seen = set()
unique_repos = []
for repo in repos:
if repo.full_name n... | @@ -1,8 +1,10 @@
from __future__ import annotations
+import os
from types import MappingProxyType
from typing import Annotated, Any, Coroutine, Literal, cast, overload
+import httpx
from pydantic import (
BaseModel,
ConfigDict,
@@ -28,6 +30,7 @@
Repository,
ResourceNotFoundError,
Sugges... | openhands/integrations/provider.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | [Fix]: token refresh for nested runtimes | 10,637 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
# Check that disabled_agent was filtered out
triggered_agents = call_args['triggered_agents']
assert len(triggered_agents) == 2
agent_names = [agent.name for agent in triggered_agents]
assert 'test_agent' in agent_names
assert 'another_agent' in agent_names
assert 'disabled_agent' not in ag... | No issues found. |
# Check that disabled_agent was filtered out
triggered_agents = call_args['triggered_agents']
assert len(triggered_agents) == 2
agent_names = [agent.name for agent in triggered_agents]
assert 'test_agent' in agent_names
assert 'another_agent' in agent_names
assert 'disabled_agent' not in ag... | @@ -1574,8 +1574,12 @@ def test_process_ipython_observation_with_vision_disabled(
vision_is_active=False,
)
- # Check that the message contains only text content
+ # Check that the message contains both text and image content
+ # (ImageContent is always included, filtering happens at Message se... | tests/unit/memory/test_conversation_memory.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Remove image content filtering in ConversationMemory | 10,645 | All-Hands-AI/OpenHands | 55,974 | Python | ryanhoangt | |
"""Initializes a new instance of the VisualBrowsingAgent class.
Parameters:
- llm (LLM): The llm to be used by this agent
"""
super().__init__(config, llm_registry)
# define a configurable action space, with chat functionality, web navigation, and webpage grounding using... | No issues found. | """Initializes a new instance of the VisualBrowsingAgent class.
Parameters:
- llm (LLM): The llm to be used by this agent
"""
super().__init__(config, llm_registry)
# define a configurable action space, with chat functionality, web navigation, and webpage grounding using... | @@ -301,10 +301,8 @@ def step(self, state: State) -> Action:
messages.append(Message(role='system', content=[TextContent(text=system_msg)]))
messages.append(Message(role='user', content=human_prompt))
- flat_messages = self.llm.format_messages_for_llm(messages)
-
response = self.llm.... | openhands/agenthub/visualbrowsing_agent/visualbrowsing_agent.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add support for passing list of `Message` into LLM `completion` | 10,650 | All-Hands-AI/OpenHands | 55,974 | Python | ryanhoangt | |
import { cn } from "#/utils/utils";
function TaskCardSkeleton() {
return (
<li className="py-3 flex items-center pr-6">
<div className="h-3 w-8 skeleton !rounded-sm" />
<div className="w-full pl-8">
<div className="h-3 w-24 skeleton mb-2 !rounded-sm" />
<div className={cn("h-3 skelet... | No issues found. | import { cn } from "#/utils/utils";
function TaskCardSkeleton() {
return (
<li className="py-3 flex items-center pr-6">
<div className="h-3 w-8 skeleton !rounded-sm" />
<div className="w-full pl-8">
<div className="h-3 w-24 skeleton mb-2 !rounded-sm" />
<div className={cn("h-3 skelet... | @@ -1,24 +1,16 @@
import { cn } from "#/utils/utils";
-const VALID_WIDTHS = ["w-1/4", "w-1/2", "w-3/4"];
-
-const getRandomWidth = () =>
- VALID_WIDTHS[Math.floor(Math.random() * VALID_WIDTHS.length)];
-
-const getRandomNumber = (from = 3, to = 5) =>
- Math.floor(Math.random() * (to - from + 1)) + from;
-
functio... | frontend/src/components/features/home/tasks/task-suggestions-skeleton.tsx | 0 | TypeScript | 1 | none | 16 | 43 | 43 | true | refactor(frontend): improve loading skeleton (conversation UX improvements) | 10,652 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
import { useQuery } from "@tanstack/react-query";
import { useConfig } from "./use-config";
import OpenHands from "#/api/open-hands";
import { useIsOnTosPage } from "#/hooks/use-is-on-tos-page";
export const useSubscriptionAccess = () => {
const { data: config } = useConfig();
const isOnTosPage = useIsOnTosPage();... | No issues found. | import { useQuery } from "@tanstack/react-query";
import { useConfig } from "./use-config";
import OpenHands from "#/api/open-hands";
import { useIsOnTosPage } from "#/hooks/use-is-on-tos-page";
export const useSubscriptionAccess = () => {
const { data: config } = useConfig();
const isOnTosPage = useIsOnTosPage();... | @@ -0,0 +1,18 @@
+import { useQuery } from "@tanstack/react-query";
+import { useConfig } from "./use-config";
+import OpenHands from "#/api/open-hands";
+import { useIsOnTosPage } from "#/hooks/use-is-on-tos-page";
+
+export const useSubscriptionAccess = () => {
+ const { data: config } = useConfig();
+ const isOnTo... | frontend/src/hooks/query/use-subscription-access.ts | 0 | TypeScript | 1 | none | 16 | 19 | 19 | true | UI for determining if llm options are enabled | 10,665 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | |
import { useSelector } from "react-redux";
import { useTranslation } from "react-i18next";
import { RootState } from "#/store";
import { useTerminal } from "#/hooks/use-terminal";
import "@xterm/xterm/css/xterm.css";
import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";
import { cn } from "#/utils/utils";
impo... | No issues found. | import { useSelector } from "react-redux";
import { useTranslation } from "react-i18next";
import { RootState } from "#/store";
import { useTerminal } from "#/hooks/use-terminal";
import "@xterm/xterm/css/xterm.css";
import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";
import { cn } from "#/utils/utils";
impo... | @@ -1,70 +1,30 @@
import { useSelector } from "react-redux";
import { useTranslation } from "react-i18next";
-import { useState } from "react";
-import { ChevronDown } from "lucide-react";
import { RootState } from "#/store";
import { useTerminal } from "#/hooks/use-terminal";
import "@xterm/xterm/css/xterm.css";
... | frontend/src/components/features/terminal/terminal.tsx | 0 | TypeScript | 1 | none | 16 | 50 | 50 | true | refactor(frontend): terminal as separate tab (conversation UX improvements) | 10,674 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
assert (
conversation_stats.service_to_metrics[
service_id
].accumulated_token_usage.completion_tokens
== 50
)
# Get combined metrics and verify
combined = conversation_stats.get_combined_metrics()
assert combined.accumulated_cost == 0.05
assert combined.accu... | No issues found. | assert (
conversation_stats.service_to_metrics[
service_id
].accumulated_token_usage.completion_tokens
== 50
)
# Get combined metrics and verify
combined = conversation_stats.get_combined_metrics()
assert combined.accumulated_cost == 0.05
assert combined.accu... | @@ -488,3 +488,125 @@ def test_save_and_restore_workflow(mock_file_store):
assert llm.metrics.accumulated_cost == 0.05
assert llm.metrics.accumulated_token_usage.prompt_tokens == 100
assert llm.metrics.accumulated_token_usage.completion_tokens == 50
+
+
+def test_save_metrics_preserves_restor... | tests/unit/test_conversation_stats.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | (Hotfix): ConversationStats metrics loss for unregistered services | 10,676 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
describe("MaintenanceBanner", () => {
afterEach(() => {
localStorage.clear();
});
it("renders maintenance banner with formatted time", () => {
const startTime = "2024-01-15T10:00:00-05:00"; // EST timestamp
const { container } = render(<MaintenanceBanner startTime={startTime} />);
// Check if ... | No issues found. |
describe("MaintenanceBanner", () => {
afterEach(() => {
localStorage.clear();
});
it("renders maintenance banner with formatted time", () => {
const startTime = "2024-01-15T10:00:00-05:00"; // EST timestamp
const { container } = render(<MaintenanceBanner startTime={startTime} />);
// Check if ... | @@ -89,23 +89,4 @@ describe("MaintenanceBanner", () => {
expect(screen.queryByTestId("maintenance-banner")).toBeInTheDocument();
});
- it("banner doesn't reappear after dismissing on next maintenance event(past time)", () => {
- const startTime = "2024-01-15T10:00:00-05:00"; // EST timestamp
- const ne... | frontend/__tests__/components/features/maintenance/maintenance-banner.test.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(frontend): maintenance banner cannot be dismissed (conversation UX improvements) | 10,677 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
import { FaBitbucket, FaGithub, FaGitlab } from "react-icons/fa6";
import { TaskCard } from "./task-card";
import { TaskItemTitle } from "./task-item-title";
import { SuggestedTask } from "#/utils/types";
interface TaskGroupProps {
title: string;
tasks: SuggestedTask[];
}
export function TaskGroup({ title, tasks ... | No issues found. | import { FaBitbucket, FaGithub, FaGitlab } from "react-icons/fa6";
import { TaskCard } from "./task-card";
import { TaskItemTitle } from "./task-item-title";
import { SuggestedTask } from "#/utils/types";
interface TaskGroupProps {
title: string;
tasks: SuggestedTask[];
}
export function TaskGroup({ title, tasks ... | @@ -13,7 +13,7 @@ export function TaskGroup({ title, tasks }: TaskGroupProps) {
return (
<div className="text-content-2 px-[14px]">
- <div className="flex items-center gap-2 border-b-1 border-[#717888]">
+ <div className="flex items-center gap-2 border-b-1 border-[#717888] mb-2">
{gitProvid... | frontend/src/components/features/home/tasks/task-group.tsx | 0 | TypeScript | 1 | none | 16 | 31 | 31 | true | refactor(frontend): make whole suggested tasks clickable (conversation UX improvements) | 10,679 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
}, [isUpdate, t]);
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!query.trim()) {
return;
}
onConfirm({
query: query.trim(),
triggers,
microagentPath: microagent?.path || "",
});
};
const handleConfirm = () => {
if... | No issues found. | }, [isUpdate, t]);
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!query.trim()) {
return;
}
onConfirm({
query: query.trim(),
triggers,
microagentPath: microagent?.path || "",
});
};
const handleConfirm = () => {
if... | @@ -1,4 +1,4 @@
-import { useEffect, useRef, useState, useMemo } from "react";
+import { useEffect, useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";
import { FaCircleInfo } from "react-icons/fa6";
@@ -11,14 +11,8 @@ import XIcon from "#/icon... | frontend/src/components/features/microagent-management/microagent-management-upsert-microagent-modal.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor: remove branch dropdown, update title, fix pr_number issue (microagent management) | 10,691 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
assert res.has_next_page is True
assert res.current_page == 2
assert res.per_page == 2
assert res.total_count == 42
assert len(res.branches) == 2
assert res.branches[0] == Branch(
name='main',
commit_sha='abc',
protected=True,
... | No issues found. | assert res.has_next_page is True
assert res.current_page == 2
assert res.per_page == 2
assert res.total_count == 42
assert len(res.branches) == 2
assert res.branches[0] == Branch(
name='main',
commit_sha='abc',
protected=True,
... | @@ -25,8 +25,8 @@ async def test_get_paginated_branches_gitlab_headers_and_parsing():
]
headers = {
- 'X-Next-Page': '3', # indicates has next page
'X-Total': '42',
+ 'Link': '<https://gitlab.example.com/api/v4/projects/group%2Frepo/repository/branches?page=3&per_page=2>; rel="next"'... | tests/unit/integrations/gitlab/test_gitlab_branches.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | (Hotfix): Branch pagination for GitLab | 10,710 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
with (
patch.object(service, '_fetch_paginated_repos', return_value=mock_repo_data),
patch.object(service, 'get_installations', return_value=[123]),
):
repositories = await service.get_all_repositories('pushed', AppMode.SAAS)
# Verify we got the expected number of repositories
... | No issues found. | with (
patch.object(service, '_fetch_paginated_repos', return_value=mock_repo_data),
patch.object(service, 'get_installations', return_value=[123]),
):
repositories = await service.get_all_repositories('pushed', AppMode.SAAS)
# Verify we got the expected number of repositories
... | @@ -340,3 +340,93 @@ async def test_github_get_user_organizations_error_handling():
# Should return empty list on error
assert orgs == []
+
+
+@pytest.mark.asyncio
+async def test_github_service_base_url_configuration():
+ """Test that BASE_URL is correctly configured based on base_domain."""
+ ... | tests/unit/integrations/github/test_github_service.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix GraphQL URL configuration for GitHub Enterprise Server | 10,725 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
# Default attributes (subclasses may override)
token: SecretStr = SecretStr('')
refresh: bool = False
external_auth_id: str | None = None
external_auth_token: SecretStr | None = None
external_token_manager: bool = False
base_domain: str | None = None
# Provider identification must be im... | No issues found. | # Default attributes (subclasses may override)
token: SecretStr = SecretStr('')
refresh: bool = False
external_auth_id: str | None = None
external_auth_token: SecretStr | None = None
external_token_manager: bool = False
base_domain: str | None = None
# Provider identification must be im... | @@ -0,0 +1,99 @@
+"""HTTP Client Protocol for Git Service Integrations."""
+
+from abc import ABC, abstractmethod
+from typing import Any
+
+from httpx import AsyncClient, HTTPError, HTTPStatusError
+from pydantic import SecretStr
+
+from openhands.core.logger import openhands_logger as logger
+from openhands.integrati... | openhands/integrations/protocols/http_client.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | refactor: introduce HTTPClient protocol for git service integrations | 10,731 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
async def get_paginated_repos(
self,
page: int,
per_page: int,
sort: str,
installation_id: str | None,
query: str | None = None,
) -> list[Repository]:
"""Get paginated repositories for a specific workspace.
Args:
page: The page number... | No issues found. | async def get_paginated_repos(
self,
page: int,
per_page: int,
sort: str,
installation_id: str | None,
query: str | None = None,
) -> list[Repository]:
"""Get paginated repositories for a specific workspace.
Args:
page: The page number... | @@ -1,5 +1,6 @@
import re
from typing import Any
+from urllib.parse import urlparse
from openhands.integrations.bitbucket.service.base import BitBucketMixinBase
from openhands.integrations.service_types import Repository, SuggestedTask
@@ -18,18 +19,28 @@ async def search_repositories(
repositories = []
... | openhands/integrations/bitbucket/service/repos.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix fragile URL parsing in Bitbucket service search_repositories method | 10,733 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
const shouldHideMicroagentManagement =
config?.FEATURE_FLAGS.HIDE_MICROAGENT_MANAGEMENT;
React.useEffect(() => {
if (shouldHideLlmSettings) return;
if (location.pathname === "/settings") {
setSettingsModalIsOpen(false);
} else if (
!isFetchingSettings &&
settingsIsError &&
... | No issues found. | const shouldHideMicroagentManagement =
config?.FEATURE_FLAGS.HIDE_MICROAGENT_MANAGEMENT;
React.useEffect(() => {
if (shouldHideLlmSettings) return;
if (location.pathname === "/settings") {
setSettingsModalIsOpen(false);
} else if (
!isFetchingSettings &&
settingsIsError &&
... | @@ -13,6 +13,7 @@ import { useLogout } from "#/hooks/mutation/use-logout";
import { useConfig } from "#/hooks/query/use-config";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { MicroagentManagementButton } from "#/components/shared/buttons/microagent-management-button";
+import { cn } fro... | frontend/src/components/features/sidebar/sidebar.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): add margin at both the top and bottom of the conversation list panel | 10,741 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
const filterText = inputValue.startsWith("https://")
? processedSearchInput
: inputValue;
return repositories.filter((repo) =>
repo.full_name.toLowerCase().includes(filterText.toLowerCase()),
);
}, [
repositories,
inputValue,
selectedRepository,
urlSearchResults,
pro... | No issues found. | const filterText = inputValue.startsWith("https://")
? processedSearchInput
: inputValue;
return repositories.filter((repo) =>
repo.full_name.toLowerCase().includes(filterText.toLowerCase()),
);
}, [
repositories,
inputValue,
selectedRepository,
urlSearchResults,
pro... | @@ -22,6 +22,7 @@ import RepoIcon from "#/icons/repo.svg?react";
export interface GitRepoDropdownProps {
provider: Provider;
value?: string | null;
+ repositoryName?: string | null;
placeholder?: string;
className?: string;
disabled?: boolean;
@@ -31,6 +32,7 @@ export interface GitRepoDropdownProps {
... | frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(frontend): double loading spinner after selecting a repo | 10,742 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
// The "Add GitHub repos" link should be in the dropdown
await waitFor(() => {
expect(screen.getByText("HOME$ADD_GITHUB_REPOS")).toBeInTheDocument();
});
});
it("should not render the 'add github repos' link if github provider is not set", async () => {
const getConfiSpy = vi.spyOn(OpenHands,... | No issues found. | // The "Add GitHub repos" link should be in the dropdown
await waitFor(() => {
expect(screen.getByText("HOME$ADD_GITHUB_REPOS")).toBeInTheDocument();
});
});
it("should not render the 'add github repos' link if github provider is not set", async () => {
const getConfiSpy = vi.spyOn(OpenHands,... | @@ -169,11 +169,12 @@ describe("RepoConnector", () => {
expect(launchButton).toBeEnabled();
});
- it("should render the 'add github repos' link if saas mode and github provider is set", async () => {
+ it("should render the 'add github repos' link in dropdown if saas mode and github provider is set", async ... | frontend/__tests__/components/features/home/repo-connector.test.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: move 'Add GitHub repos' button to repo selector dropdown | 10,762 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | |
],
has_next_page: false,
current_page: 1,
per_page: 30,
total_count: 2,
});
renderHomeScreen();
const taskSuggestions = await screen.findByTestId("task-suggestions");
// Initially, all tasks should be visible
await waitFor(() => {
within(taskSuggestions).getByT... | No issues found. | ],
has_next_page: false,
current_page: 1,
per_page: 30,
total_count: 2,
});
renderHomeScreen();
const taskSuggestions = await screen.findByTestId("task-suggestions");
// Initially, all tasks should be visible
await waitFor(() => {
within(taskSuggestions).getByT... | @@ -351,16 +351,6 @@ describe("HomeScreen", () => {
});
});
});
-
- it("should hide the suggested tasks section if not authed with git(hub|lab)", async () => {
- renderHomeScreen();
-
- const taskSuggestions = screen.queryByTestId("task-suggestions");
- const repoConnector = screen.getByTestId(... | frontend/__tests__/routes/home-screen.test.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(frontend): home screen component sizes | 10,763 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
);
// Handle menu scroll for infinite loading
const handleMenuScroll = useCallback(
(event: React.UIEvent<HTMLUListElement>) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
if (
scrollHeight - scrollTop <= clientHeight * 1.5 &&
hasNextPage &&
!i... | No issues found. | );
// Handle menu scroll for infinite loading
const handleMenuScroll = useCallback(
(event: React.UIEvent<HTMLUListElement>) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
if (
scrollHeight - scrollTop <= clientHeight * 1.5 &&
hasNextPage &&
!i... | @@ -11,7 +11,7 @@ import { Provider } from "#/types/settings";
import { useDebounce } from "#/hooks/use-debounce";
import { cn } from "#/utils/utils";
import { useBranchData } from "#/hooks/query/use-branch-data";
-import { LoadingSpinner } from "../shared/loading-spinner";
+
import { ClearButton } from "../shared/... | frontend/src/components/features/home/git-branch-dropdown/git-branch-dropdown.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix add repos button | 10,788 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | |
},
linkColor: {
default: "",
white: "text-white",
},
},
defaultVariants: {
size: "default",
linkColor: "default",
},
});
interface HelpLinkProps extends VariantProps<typeof helpLinkVariants> {
testId: string;
text: string;
linkText: string;
href: string;
suffix?: string;... | No issues found. | },
linkColor: {
default: "",
white: "text-white",
},
},
defaultVariants: {
size: "default",
linkColor: "default",
},
});
interface HelpLinkProps extends VariantProps<typeof helpLinkVariants> {
testId: string;
text: string;
linkText: string;
href: string;
suffix?: string;... | @@ -0,0 +1,65 @@
+import { cva, type VariantProps } from "class-variance-authority";
+import { cn } from "#/utils/utils";
+
+const helpLinkVariants = cva("", {
+ variants: {
+ size: {
+ default: "text-xs",
+ settings: "text-sm text-[#A3A3A3] font-normal leading-5.5",
+ },
+ linkColor: {
+ defau... | frontend/src/ui/help-link.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(frontend): update API provider configuration modal | 10,840 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
import the UserAuth class from the openhands.server.user_auth module.
Args:
qual_name: A fully qualified name in the format 'module.submodule.name'
e.g. 'openhands.server.user_auth.UserAuth'
Returns:
The imported value (class, function, or variable)
Example:
... | No issues found. | import the UserAuth class from the openhands.server.user_auth module.
Args:
qual_name: A fully qualified name in the format 'module.submodule.name'
e.g. 'openhands.server.user_auth.UserAuth'
Returns:
The imported value (class, function, or variable)
Example:
... | @@ -31,6 +31,14 @@ def import_from(qual_name: str):
@lru_cache()
+def _get_impl(cls: type[T], impl_name: str | None) -> type[T]:
+ if impl_name is None:
+ return cls
+ impl_class = import_from(impl_name)
+ assert cls == impl_class or issubclass(impl_class, cls)
+ return impl_class
+
+
def get_i... | openhands/utils/import_utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | More Type Safety | 10,848 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | |
extra={
'does_webhook_exist_on_resource': does_webhook_exist_on_resource,
'status': status,
'resource_id': resource_id,
'resource_type': resource_type,
},
)
self.determine_if_rate_limited(status)
if does_web... | No issues found. | extra={
'does_webhook_exist_on_resource': does_webhook_exist_on_resource,
'status': status,
'resource_id': resource_id,
'resource_type': resource_type,
},
)
self.determine_if_rate_limited(status)
if does_web... | @@ -276,12 +276,12 @@ async def install_webhooks(self):
webhook
)
- gitlab_service = GitLabServiceImpl(external_auth_id=user_id)
+ gitlab_service_impl = GitLabServiceImpl(external_auth_id=user_id)
- if not isinstance(gitlab_service, ... | enterprise/sync/install_gitlab_webhooks.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | chore - MyPy check Enterprise with OpenHands | 10,858 | All-Hands-AI/OpenHands | 55,974 | Python | raymyers | |
import PlayIcon from "#/icons/play-solid.svg?react";
import { cn } from "#/utils/utils";
export interface ChatResumeAgentButtonProps {
onAgentResumed: () => void;
disabled?: boolean;
}
export function ChatResumeAgentButton({
onAgentResumed,
disabled = false,
}: ChatResumeAgentButtonProps) {
return (
<bu... | No issues found. | import PlayIcon from "#/icons/play-solid.svg?react";
import { cn } from "#/utils/utils";
export interface ChatResumeAgentButtonProps {
onAgentResumed: () => void;
disabled?: boolean;
}
export function ChatResumeAgentButton({
onAgentResumed,
disabled = false,
}: ChatResumeAgentButtonProps) {
return (
<bu... | @@ -1,14 +1,23 @@
import PlayIcon from "#/icons/play-solid.svg?react";
+import { cn } from "#/utils/utils";
export interface ChatResumeAgentButtonProps {
onAgentResumed: () => void;
+ disabled?: boolean;
}
export function ChatResumeAgentButton({
onAgentResumed,
+ disabled = false,
}: ChatResumeAgentBut... | frontend/src/components/features/chat/chat-play-button.tsx | 0 | TypeScript | 1 | none | 16 | 25 | 25 | true | refactor(frontend): enable message drafting during page load | 10,879 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
from typing import Any
from fastapi import Request
from openhands.events.action.action import Action, ActionSecurityRisk
class SecurityAnalyzer:
"""Security analyzer that analyzes agent actions for security risks."""
def __init__(self) -> None:
"""Initializes a new instance of the SecurityAnalyzer ... | No issues found. | from typing import Any
from fastapi import Request
from openhands.events.action.action import Action, ActionSecurityRisk
class SecurityAnalyzer:
"""Security analyzer that analyzes agent actions for security risks."""
def __init__(self) -> None:
"""Initializes a new instance of the SecurityAnalyzer ... | @@ -24,6 +24,14 @@ async def security_risk(self, action: Action) -> ActionSecurityRisk:
'Need to implement security_risk method in SecurityAnalyzer subclass'
)
+ def set_event_stream(self, event_stream) -> None:
+ """Set the event stream for accessing conversation history.
+
+ A... | openhands/security/analyzer.py | 0 | Python | 1 | none | 16 | 38 | 38 | true | feat: Add Cygnal integration | 10,898 | All-Hands-AI/OpenHands | 55,974 | Python | eliotjones1 | |
const typographyVariants = cva("", {
variants: {
variant: {
h1: "text-[32px] text-white font-bold leading-5",
},
},
defaultVariants: {
variant: "h1",
},
});
interface TypographyProps extends VariantProps<typeof typographyVariants> {
className?: string;
testId?: string;
children: React.... | No issues found. |
const typographyVariants = cva("", {
variants: {
variant: {
h1: "text-[32px] text-white font-bold leading-5",
},
},
defaultVariants: {
variant: "h1",
},
});
interface TypographyProps extends VariantProps<typeof typographyVariants> {
className?: string;
testId?: string;
children: React.... | @@ -0,0 +1,53 @@
+import { cva, type VariantProps } from "class-variance-authority";
+import { cn } from "#/utils/utils";
+
+const typographyVariants = cva("", {
+ variants: {
+ variant: {
+ h1: "text-[32px] text-white font-bold leading-5",
+ },
+ },
+ defaultVariants: {
+ variant: "h1",
+ },
+});
+
+... | frontend/src/ui/typography.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): home header component | 10,930 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
},
textColor: {
default: "text-white",
},
lineHeight: {
default: "leading-5",
},
},
defaultVariants: {
gap: "default",
textSize: "default",
fontWeight: "default",
textColor: "default",
lineHeight: "default",
},
});
interface CardTitleProps extends VariantProps<... | No issues found. | },
textColor: {
default: "text-white",
},
lineHeight: {
default: "leading-5",
},
},
defaultVariants: {
gap: "default",
textSize: "default",
fontWeight: "default",
textColor: "default",
lineHeight: "default",
},
});
interface CardTitleProps extends VariantProps<... | @@ -0,0 +1,77 @@
+import { ReactNode } from "react";
+import { cva, type VariantProps } from "class-variance-authority";
+import { cn } from "#/utils/utils";
+
+const cardTitleVariants = cva("flex items-center", {
+ variants: {
+ gap: {
+ default: "gap-[10px]",
+ },
+ textSize: {
+ default: "text-ba... | frontend/src/ui/card-title.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): new conversation component | 10,937 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
result = _get_workspace_mount_path_from_env(runtime_type='local')
assert result == os.getcwd()
def test_relative_path_conversion(self):
"""Test that relative paths in SANDBOX_VOLUMES are converted to absolute."""
with patch.dict(
os.environ, {'SANDBOX_VOLUMES': '... | No issues found. | result = _get_workspace_mount_path_from_env(runtime_type='local')
assert result == os.getcwd()
def test_relative_path_conversion(self):
"""Test that relative paths in SANDBOX_VOLUMES are converted to absolute."""
with patch.dict(
os.environ, {'SANDBOX_VOLUMES': '... | @@ -0,0 +1,225 @@
+"""Tests for str_replace_editor tool workspace path detection."""
+
+import os
+import sys
+from unittest.mock import patch
+
+import pytest
+
+# Import the functions directly to avoid dependency issues
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../..'))
+
+try:
+ from openhan... | tests/unit/agenthub/test_str_replace_editor_tool.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Update str_replace_editor tool to use dynamic workspace path from SANDBOX_VOLUMES | 10,965 | All-Hands-AI/OpenHands | 55,974 | Python | li-boxuan | |
import { BaseModal } from "../../../shared/modals/base-modal/base-modal";
import { RootState } from "#/store";
import { I18nKey } from "#/i18n/declaration";
import { CostSection } from "./cost-section";
import { UsageSection } from "./usage-section";
import { ContextWindowSection } from "./context-window-section";
impo... | No issues found. | import { BaseModal } from "../../../shared/modals/base-modal/base-modal";
import { RootState } from "#/store";
import { I18nKey } from "#/i18n/declaration";
import { CostSection } from "./cost-section";
import { UsageSection } from "./usage-section";
import { ContextWindowSection } from "./context-window-section";
impo... | @@ -0,0 +1,53 @@
+import { useTranslation } from "react-i18next";
+import { useSelector } from "react-redux";
+import { BaseModal } from "../../../shared/modals/base-modal/base-modal";
+import { RootState } from "#/store";
+import { I18nKey } from "#/i18n/declaration";
+import { CostSection } from "./cost-section";
+im... | frontend/src/components/features/conversation/metrics-modal/metrics-modal.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): metrics modal | 10,968 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
isError,
refetch,
isRefetching,
} = useConversationMicroagents();
const toggleAgent = (agentName: string) => {
setExpandedAgents((prev) => ({
...prev,
[agentName]: !prev[agentName],
}));
};
const isAgentReady = ![AgentState.LOADING, AgentState.INIT].includes(
curAgentState,... | No issues found. | isError,
refetch,
isRefetching,
} = useConversationMicroagents();
const toggleAgent = (agentName: string) => {
setExpandedAgents((prev) => ({
...prev,
[agentName]: !prev[agentName],
}));
};
const isAgentReady = ![AgentState.LOADING, AgentState.INIT].includes(
curAgentState,... | @@ -1,15 +1,17 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";
-import { ChevronDown, ChevronRight, RefreshCw } from "lucide-react";
-import { BaseModalTitle } from "#/components/shared/modals/confirmation-modals/base-modal";
import { M... | frontend/src/components/features/conversation-panel/microagents-modal.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): microagents modal | 10,970 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import { ChatInterfaceWrapper } from "./chat-interface-wrapper";
import { ConversationTabContent } from "../conversation-tabs/conversation-tab-content/conversation-tab-content";
interface DesktopLayoutProps {
isRightPanelShown: boolean;
}... | No issues found. | import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import { ChatInterfaceWrapper } from "./chat-interface-wrapper";
import { ConversationTabContent } from "../conversation-tabs/conversation-tab-content/conversation-tab-content";
interface DesktopLayoutProps {
isRightPanelShown: boolean;
}... | @@ -0,0 +1,35 @@
+import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
+import { ChatInterfaceWrapper } from "./chat-interface-wrapper";
+import { ConversationTabContent } from "../conversation-tabs/conversation-tab-content/conversation-tab-content";
+
+interface DesktopLayoutProps {
+ isRigh... | frontend/src/components/features/conversation/conversation-main/desktop-layout.tsx | 0 | TypeScript | 1 | none | 16 | 36 | 36 | true | refactor(frontend): conversation main | 10,985 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
RUNTIME_USERNAME = os.getenv('RUNTIME_USERNAME')
RUNTIME_UID = os.getenv('RUNTIME_UID')
def get_action_execution_server_startup_command(
server_port: int,
plugins: list[PluginRequirement],
app_config: OpenHandsConfig,
python_prefix: list[str] = DEFAULT_PYTHON_PREFIX,
override_user_id: int | None =... | No issues found. | RUNTIME_USERNAME = os.getenv('RUNTIME_USERNAME')
RUNTIME_UID = os.getenv('RUNTIME_UID')
def get_action_execution_server_startup_command(
server_port: int,
plugins: list[PluginRequirement],
app_config: OpenHandsConfig,
python_prefix: list[str] = DEFAULT_PYTHON_PREFIX,
override_user_id: int | None =... | @@ -1,3 +1,5 @@
+import os
+
from openhands.core.config import OpenHandsConfig
from openhands.core.logger import openhands_logger as logger
from openhands.runtime.plugins import PluginRequirement
@@ -12,6 +14,9 @@
]
DEFAULT_MAIN_MODULE = 'openhands.runtime.action_execution_server'
+RUNTIME_USERNAME = os.getenv('... | openhands/runtime/utils/command.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Allow custom user | 11,013 | All-Hands-AI/OpenHands | 55,974 | Python | chuckbutkus | |
it("should render modal when Redux state is set to visible", async () => {
// Render with modal already visible in Redux state
renderWithProviders(<RouterStub />, {
preloadedState: {
microagentManagement: {
selectedMicroagentItem: null,
addMicroagentModalVisible... | No issues found. | it("should render modal when Redux state is set to visible", async () => {
// Render with modal already visible in Redux state
renderWithProviders(<RouterStub />, {
preloadedState: {
microagentManagement: {
selectedMicroagentItem: null,
addMicroagentModalVisible... | @@ -57,11 +57,6 @@ describe("MicroagentManagement", () => {
const renderMicroagentManagement = (config?: QueryClientConfig) =>
renderWithProviders(<RouterStub />, {
preloadedState: {
- metrics: {
- cost: null,
- max_budget_per_task: null,
- usage: null,
- },
... | frontend/__tests__/components/features/microagent-management/microagent-management.test.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): migration of metrics-slice.ts to zustand | 11,018 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
def test_timeout_validation_positive_values(self):
"""Test timeout validation accepts positive values."""
# Test various valid timeout values
valid_timeouts = [1, 5, 30, 60, 120, 300, 600, 1800, 3600]
for timeout in valid_timeouts:
config = MCPSHTTPServerConfig(
... | No issues found. | def test_timeout_validation_positive_values(self):
"""Test timeout validation accepts positive values."""
# Test various valid timeout values
valid_timeouts = [1, 5, 30, 60, 120, 300, 600, 1800, 3600]
for timeout in valid_timeouts:
config = MCPSHTTPServerConfig(
... | @@ -0,0 +1,122 @@
+"""Test MCP SHTTP server timeout configuration."""
+
+import pytest
+from pydantic import ValidationError
+
+from openhands.core.config.mcp_config import MCPSHTTPServerConfig
+
+
+class TestMCPSHTTPServerConfig:
+ """Test SHTTP server configuration with timeout field."""
+
+ def test_shttp_conf... | tests/unit/core/config/test_shttp_timeout_config.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | feat: Add configurable timeouts for MCP tool invocations (Good first issues: #10684) | 11,029 | All-Hands-AI/OpenHands | 55,974 | Python | tejas-goyal | |
repositoryName: string,
microagentPath: string,
): string => {
const baseUrl = getGitProviderBaseUrl(gitProvider);
switch (gitProvider) {
case "github":
return `${baseUrl}/${repositoryName}/blob/main/${microagentPath}`;
case "gitlab":
return `${baseUrl}/${repositoryName}/-/blob/main/${micro... | No issues found. | repositoryName: string,
microagentPath: string,
): string => {
const baseUrl = getGitProviderBaseUrl(gitProvider);
switch (gitProvider) {
case "github":
return `${baseUrl}/${repositoryName}/blob/main/${microagentPath}`;
case "gitlab":
return `${baseUrl}/${repositoryName}/-/blob/main/${micro... | @@ -10,6 +10,34 @@ export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+/**
+ * Get the numeric height value from an element's style property
+ * @param el The HTML element to get the height from
+ * @param fallback The fallback value to return if style height is invalid
+ * @returns The... | frontend/src/utils/utils.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | patilatharv | |
unexpected=[],
),
# Agent has none; should show "None configured on the current agent"
dict(
id="agent_has_none",
agent_mcp={},
file_content=None,
expected=[
"Current Agent MCP Servers:",
"None configured on the current agent",
],
... | No issues found. | unexpected=[],
),
# Agent has none; should show "None configured on the current agent"
dict(
id="agent_has_none",
agent_mcp={},
file_content=None,
expected=[
"Current Agent MCP Servers:",
"None configured on the current agent",
],
... | @@ -0,0 +1,199 @@
+"""Parametrized tests for MCP configuration screen functionality."""
+
+import json
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from openhands_cli.locations import MCP_CONFIG_FILE
+from openhands_cli.tui.settings.mcp_screen import MCPScreen
+from openhands.sdk impor... | openhands-cli/tests/test_mcp_config_validation.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add /mcp command for MCP server configuration in CLI | 11,105 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
mock_conversation = MagicMock()
mock_setup_conversation.return_value = mock_conversation
# Mock prompt session to raise KeyboardInterrupt to exit the loop
mock_prompt_session.return_value.prompt.side_effect = KeyboardInterrupt()
# Should complete without raising an exce... | No issues found. | mock_conversation = MagicMock()
mock_setup_conversation.return_value = mock_conversation
# Mock prompt session to raise KeyboardInterrupt to exit the loop
mock_prompt_session.return_value.prompt.side_effect = KeyboardInterrupt()
# Should complete without raising an exce... | @@ -10,25 +10,25 @@
class TestMainEntryPoint:
"""Test the main entry point behavior."""
- @patch('openhands_cli.agent_chat.setup_agent')
+ @patch('openhands_cli.agent_chat.setup_conversation')
@patch('openhands_cli.agent_chat.ConversationRunner')
@patch('openhands_cli.agent_chat.PromptSession')
... | openhands-cli/tests/test_main.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v1 cli: provide information on CWD | 11,108 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | |
style = "class:selected" if is_selected else "class:unselected"
lines.append((style, f"{prefix}{choice}\n"))
return lines
content_window = Window(
FormattedTextControl(get_choice_text),
always_hide_cursor=True,
height=Dimension(max=8),
)
return Layout... | No issues found. | style = "class:selected" if is_selected else "class:unselected"
lines.append((style, f"{prefix}{choice}\n"))
return lines
content_window = Window(
FormattedTextControl(get_choice_text),
always_hide_cursor=True,
height=Dimension(max=8),
)
return Layout... | @@ -1,3 +1,5 @@
+from openhands_cli.tui.tui import CommandCompleter
+from prompt_toolkit import PromptSession
from prompt_toolkit.application import Application
from prompt_toolkit.completion import Completer
from prompt_toolkit.input.base import Input
@@ -128,12 +130,16 @@ def cli_text_input(
@kb.add('c-... | openhands-cli/openhands_cli/user_actions/utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | CLI(V1): restore terminal state | 11,127 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
conversation = None
settings_screen = SettingsScreen()
while not conversation:
try:
conversation = setup_conversation()
except MissingAgentSpec:
settings_screen.handle_basic_settings(escapable=False)
display_welcome(conversation.id)
# Create conversation r... | No issues found. |
conversation = None
settings_screen = SettingsScreen()
while not conversation:
try:
conversation = setup_conversation()
except MissingAgentSpec:
settings_screen.handle_basic_settings(escapable=False)
display_welcome(conversation.id)
# Create conversation r... | @@ -60,10 +60,7 @@ def run_cli_entry() -> None:
except MissingAgentSpec:
settings_screen.handle_basic_settings(escapable=False)
- # Generate session ID
- session_id = str(uuid.uuid4())[:8]
-
- display_welcome(session_id)
+ display_welcome(conversation.id)
# Create conversation... | openhands-cli/openhands_cli/agent_chat.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | CLI(V1): session persistence | 11,129 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
4) return the result or raise the expected exception.
Returns:
- The prompt result (str) if no exception expected.
- None if an exception is expected and raised.
"""
with create_pipe_input() as pipe:
session = get_session_prompter(input=pipe, output=DummyOutput())
with Thr... | No issues found. | 4) return the result or raise the expected exception.
Returns:
- The prompt result (str) if no exception expected.
- None if an exception is expected and raised.
"""
with create_pipe_input() as pipe:
session = get_session_prompter(input=pipe, output=DummyOutput())
with Thr... | @@ -0,0 +1,102 @@
+import time
+from concurrent.futures import ThreadPoolExecutor
+from typing import Optional, Type
+
+import pytest
+from prompt_toolkit.formatted_text import HTML
+from prompt_toolkit.input.defaults import create_pipe_input
+from prompt_toolkit.output.defaults import DummyOutput
+
+from openhands_cli... | openhands-cli/tests/test_session_prompter.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | CLI(V1): Multiline inputs | 11,131 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
from openhands_cli.listeners.loading_listener import (
LoadingContext,
display_initialization_animation
)
class TestLoadingAnimation(unittest.TestCase):
"""Test cases for loading animation functionality."""
def test_loading_context_manager(self):
"""Test that LoadingContext works as a context ... | No issues found. | from openhands_cli.listeners.loading_listener import (
LoadingContext,
display_initialization_animation
)
class TestLoadingAnimation(unittest.TestCase):
"""Test cases for loading animation functionality."""
def test_loading_context_manager(self):
"""Test that LoadingContext works as a context ... | @@ -0,0 +1,69 @@
+#!/usr/bin/env python3
+"""
+Unit tests for the loading animation functionality.
+"""
+
+import threading
+import time
+import unittest
+from unittest.mock import patch
+
+from openhands_cli.listeners.loading_listener import (
+ LoadingContext,
+ display_initialization_animation
+)
+
+class Test... | openhands-cli/tests/test_loading.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | CLI(V1): Add loading screen + suppress extraneous logs | 11,134 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
const repoSuggestions = Object.keys(SUGGESTIONS.repo);
// check that there are at most 4 suggestions displayed
const displayedSuggestions = within(suggestions).getAllByRole("button");
expect(displayedSuggestions.length).toBeLessThanOrEqual(4);
// Check that each displayed suggestion is one of the ... | No issues found. | const repoSuggestions = Object.keys(SUGGESTIONS.repo);
// check that there are at most 4 suggestions displayed
const displayedSuggestions = within(suggestions).getAllByRole("button");
expect(displayedSuggestions.length).toBeLessThanOrEqual(4);
// Check that each displayed suggestion is one of the ... | @@ -17,17 +17,17 @@ import type { Message } from "#/message";
import { SUGGESTIONS } from "#/utils/suggestions";
import { ChatInterface } from "#/components/features/chat/chat-interface";
import { useWsClient } from "#/context/ws-client-provider";
+import { useErrorMessageStore } from "#/stores/error-message-store";... | frontend/__tests__/components/chat/chat-interface.test.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(frontend): migration of use-ws-error-message.ts to zustand | 11,147 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
# Should complete without raising an exception (graceful exit)
simple_main.main()
# Should call run_cli_entry with no resume conversation ID
mock_run_agent_chat.assert_called_once_with(resume_conversation_id=None)
@patch('openhands_cli.simple_main.run_cli_entry')
@patch('sys.a... | No issues found. |
# Should complete without raising an exception (graceful exit)
simple_main.main()
# Should call run_cli_entry with no resume conversation ID
mock_run_agent_chat.assert_called_once_with(resume_conversation_id=None)
@patch('openhands_cli.simple_main.run_cli_entry')
@patch('sys.a... | @@ -11,30 +11,23 @@
class TestMainEntryPoint:
"""Test the main entry point behavior."""
- @patch('openhands_cli.agent_chat.setup_conversation')
- @patch('openhands_cli.agent_chat.ConversationRunner')
- @patch('openhands_cli.agent_chat.get_session_prompter')
+ @patch('openhands_cli.simple_main.run_cl... | openhands-cli/tests/test_main.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | CLI(V1): resume conversations | 11,154 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | |
# Mock the stores to return our test settings
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_se... | No issues found. |
# Mock the stores to return our test settings
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_se... | @@ -0,0 +1,162 @@
+"""Unit tests for conversation_service.py - specifically testing provider token handling.
+
+These tests verify that setup_init_conversation_settings correctly handles provider tokens
+in different scenarios (provided tokens vs scaffold creation).
+"""
+
+from types import MappingProxyType
+from unit... | tests/unit/server/services/test_conversation_service.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | fix: add provider tokens to resume conversation endpoint | 11,155 | All-Hands-AI/OpenHands | 55,974 | Python | ak684 | |
from typing import Any
def get_llm_metadata(
model_name: str,
llm_type: str,
session_id: str | None = None,
user_id: str | None = None,
) -> dict[str, Any]:
"""
Generate LLM metadata for OpenHands CLI.
Args:
model_name: Name of the LLM model
agent_name: Name of the agent (... | No issues found. | from typing import Any
def get_llm_metadata(
model_name: str,
llm_type: str,
session_id: str | None = None,
user_id: str | None = None,
) -> dict[str, Any]:
"""
Generate LLM metadata for OpenHands CLI.
Args:
model_name: Name of the LLM model
agent_name: Name of the agent (... | @@ -0,0 +1,55 @@
+"""Utility functions for LLM configuration in OpenHands CLI."""
+
+import os
+from typing import Any
+
+
+def get_llm_metadata(
+ model_name: str,
+ llm_type: str,
+ session_id: str | None = None,
+ user_id: str | None = None,
+) -> dict[str, Any]:
+ """
+ Generate LLM metadata for O... | openhands-cli/openhands_cli/llm_utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Update OpenHands CLI for agent SDK refactor | 11,165 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | |
import { GitRepository } from "#/types/git";
interface HomeState {
recentRepositories: GitRepository[];
}
interface HomeActions {
addRecentRepository: (repository: GitRepository) => void;
clearRecentRepositories: () => void;
getRecentRepositories: () => GitRepository[];
}
type HomeStore = HomeState & HomeAct... | No issues found. | import { GitRepository } from "#/types/git";
interface HomeState {
recentRepositories: GitRepository[];
}
interface HomeActions {
addRecentRepository: (repository: GitRepository) => void;
clearRecentRepositories: () => void;
getRecentRepositories: () => GitRepository[];
}
type HomeStore = HomeState & HomeAct... | @@ -0,0 +1,53 @@
+import { create } from "zustand";
+import { persist, createJSONStorage } from "zustand/middleware";
+import { GitRepository } from "#/types/git";
+
+interface HomeState {
+ recentRepositories: GitRepository[];
+}
+
+interface HomeActions {
+ addRecentRepository: (repository: GitRepository) => void;
... | frontend/src/stores/home-store.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(frontend): persist recent repos | 11,171 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
mock_client = AsyncMock(spec=httpx.AsyncClient)
# Simulate resume scenario: secret already exists (400)
mock_response = MockHTTPXResponse(
400, {'message': 'Secret MY_API_KEY already exists'}
)
async def mock_post(*args, **kwargs):
return mock_response
mock_client.post = Async... | No issues found. | mock_client = AsyncMock(spec=httpx.AsyncClient)
# Simulate resume scenario: secret already exists (400)
mock_response = MockHTTPXResponse(
400, {'message': 'Secret MY_API_KEY already exists'}
)
async def mock_post(*args, **kwargs):
return mock_response
mock_client.post = Async... | @@ -0,0 +1,176 @@
+"""Tests for SaasNestedConversationManager custom secrets handling during resume."""
+
+from types import MappingProxyType
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx
+import pytest
+from pydantic import SecretStr
+from server.saas_nested_conversation_manager import SaasNestedConv... | enterprise/tests/unit/test_saas_conversation_manager_secrets.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | increase remote_runtime_api_timeout and handle duplicate secrets | 11,239 | All-Hands-AI/OpenHands | 55,974 | Python | ak684 | |
current_job_state = None # Initialize
finished_job_id = (
self.active_job.Id
) # Store ID before potentially clearing self.active_job
if active_job_obj:
current_job_state = active_job_obj.JobStateInfo.State
... | No issues found. | current_job_state = None # Initialize
finished_job_id = (
self.active_job.Id
) # Store ID before potentially clearing self.active_job
if active_job_obj:
current_job_state = active_job_obj.JobStateInfo.State
... | @@ -6,7 +6,6 @@
import os
import time
-import traceback
from pathlib import Path
from threading import RLock
@@ -155,8 +154,7 @@ def __init__(
self._initialized = True # Set to True only on successful initialization
logger.info(f'PowerShell runspace created. Initial CWD set to: {self.... | openhands/runtime/utils/windows_bash.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | feat(logging): JSON log config for Uvicorn when LOG_JSON=1 | 11,264 | All-Hands-AI/OpenHands | 55,974 | Python | neubig | |
)
# Create a command that references multiple tokens
cmd = CmdRunAction(command='echo $GITHUB_TOKEN && echo $GITLAB_TOKEN')
# Export the tokens
await runtime._export_latest_git_provider_tokens(cmd)
# Verify that both tokens were exported
assert event_stream.secrets == {
'github_to... | No issues found. | )
# Create a command that references multiple tokens
cmd = CmdRunAction(command='echo $GITHUB_TOKEN && echo $GITLAB_TOKEN')
# Export the tokens
await runtime._export_latest_git_provider_tokens(cmd)
# Verify that both tokens were exported
assert event_stream.secrets == {
'github_to... | @@ -8,7 +8,11 @@
from openhands.core.config.mcp_config import MCPConfig, MCPStdioServerConfig
from openhands.events.action import Action
from openhands.events.action.commands import CmdRunAction
-from openhands.events.observation import NullObservation, Observation
+from openhands.events.observation import (
+ Cm... | tests/unit/runtime/test_runtime_git_tokens.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | fix: refresh provider tokens proactively and update git URLs on resume | 11,296 | All-Hands-AI/OpenHands | 55,974 | Python | ak684 | |
sort='updated',
order='desc',
public=True,
app_mode=AppMode.OSS,
)
# Verify the correct workspace/repo combination was extracted and passed
assert len(repositories) == 1
assert repositories[0].full_name == 'workspace/repo'
mock_get... | No issues found. | sort='updated',
order='desc',
public=True,
app_mode=AppMode.OSS,
)
# Verify the correct workspace/repo combination was extracted and passed
assert len(repositories) == 1
assert repositories[0].full_name == 'workspace/repo'
mock_get... | @@ -8,6 +8,7 @@
from openhands.integrations.bitbucket.bitbucket_service import BitBucketService
from openhands.integrations.service_types import OwnerType, Repository
from openhands.integrations.service_types import ProviderType as ServiceProviderType
+from openhands.server.types import AppMode
@pytest.fixture
... | tests/unit/integrations/bitbucket/test_bitbucket_repos.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | fix(backend): repository search is not working in the production environment | 11,386 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | |
sandbox: SandboxConfig = Field(default_factory=SandboxConfig)
security: SecurityConfig = Field(default_factory=SecurityConfig)
extended: ExtendedConfig = Field(default_factory=lambda: ExtendedConfig({}))
runtime: str = Field(default='docker')
file_store: str = Field(default='local')
file_store_p... | No issues found. | sandbox: SandboxConfig = Field(default_factory=SandboxConfig)
security: SecurityConfig = Field(default_factory=SecurityConfig)
extended: ExtendedConfig = Field(default_factory=lambda: ExtendedConfig({}))
runtime: str = Field(default='docker')
file_store: str = Field(default='local')
file_store_p... | @@ -112,6 +112,10 @@ class OpenHandsConfig(BaseModel):
max_concurrent_conversations: int = Field(
default=3
) # Maximum number of concurrent agent loops allowed per user
+ client_wait_timeout: int = Field(
+ default=30,
+ description='Timeout in seconds for waiting for websocket cli... | openhands/core/config/openhands_config.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | feat: make websocket client wait timeout configurable | 11,405 | All-Hands-AI/OpenHands | 55,974 | Python | olyashok | |
if isinstance(write_obs, ErrorObservation):
self.log('error', f'Failed to write pre-commit hook: {write_obs.content}')
return
# Make the pre-commit hook executable
action = CmdRunAction(f'chmod +x {pre_commit_hook}')
obs = self.run_action(action)
if isins... | No issues found. | if isinstance(write_obs, ErrorObservation):
self.log('error', f'Failed to write pre-commit hook: {write_obs.content}')
return
# Make the pre-commit hook executable
action = CmdRunAction(f'chmod +x {pre_commit_hook}')
obs = self.run_action(action)
if isins... | @@ -747,6 +747,7 @@ def get_microagents_from_org_or_user(
self.provider_handler.get_authenticated_git_url,
GENERAL_TIMEOUT,
org_openhands_repo,
+ is_optional=True,
)
except AuthenticationError as e:
... | openhands/runtime/base.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix excessive error logging for missing org-level microagents | 11,425 | All-Hands-AI/OpenHands | 55,974 | Python | neubig | |
result = ask_user_confirmation([mock_action])
assert result.decision == UserConfirmation.DEFER
assert isinstance(result, ConfirmationResult)
assert result.reason == ''
assert result.policy_change is None
@patch('openhands_cli.user_actions.agent_action.cli_confirm')
def ... | No issues found. |
result = ask_user_confirmation([mock_action])
assert result.decision == UserConfirmation.DEFER
assert isinstance(result, ConfirmationResult)
assert result.reason == ''
assert result.policy_change is None
@patch('openhands_cli.user_actions.agent_action.cli_confirm')
def ... | @@ -147,10 +147,12 @@ def test_ask_user_confirmation_yes(self, mock_cli_confirm: Any) -> None:
assert result.policy_change is None
assert result.policy_change is None
+ @patch('openhands_cli.user_actions.agent_action.cli_text_input')
@patch('openhands_cli.user_actions.agent_action.cli_confir... | openhands-cli/tests/test_confirmation_mode.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Simplify security analyzer confirmation: replace two reject options with single 'Reject' option | 11,443 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.