Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions integrations/slack/slack_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from dataclasses import dataclass, field
from uuid import UUID, uuid4

import httpx
from jinja2 import Environment
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
Expand Down Expand Up @@ -35,6 +36,7 @@
from openhands.app_server.utils.async_utils import GENERAL_TIMEOUT
from openhands.app_server.utils.logger import openhands_logger as logger
from openhands.sdk import ImageContent, TextContent
from openhands.sdk.utils.redact import redact_api_key_literals, redact_text_secrets
from storage.slack_conversation import SlackConversation
from storage.slack_conversation_store import SlackConversationStore
from storage.slack_team_store import SlackTeamStore
Expand Down Expand Up @@ -287,8 +289,8 @@ async def _create_v1_conversation(self, jinja: Environment) -> None:
):
if task.status == AppConversationStartTaskStatus.ERROR:
logger.error(f'Failed to start V1 conversation: {task.detail}')
raise RuntimeError(
f'Failed to start V1 conversation: {task.detail}'
raise StartingConvoException(
f'Failed to start the conversation: {task.detail}'
)

logger.info(f'[Slack V1]: Created new conversation: {self.conversation_id}')
Expand Down Expand Up @@ -354,6 +356,7 @@ async def send_message_to_v1_conversation(self, jinja: Environment):
get_sandbox_service,
)
from openhands.app_server.event_callback.util import (
agent_server_error_detail,
ensure_conversation_found,
get_agent_server_url_from_sandbox,
)
Expand Down Expand Up @@ -419,6 +422,20 @@ async def send_message_to_v1_conversation(self, jinja: Environment):
)
response.raise_for_status()

except httpx.HTTPStatusError as e:
detail = redact_text_secrets(
redact_api_key_literals(agent_server_error_detail(e))
)
logger.exception(
'[Slack V1] Failed to send message to conversation %s: %s',
self.conversation_id,
detail,
stack_info=True,
)
raise StartingConvoException(
f'Failed to send your message to the conversation: {detail}'
) from e

except Exception as e:
logger.exception(
'[Slack V1] Failed to send message to conversation %s: %s',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
from openhands.app_server.event_callback.set_title_callback_processor import (
SetTitleCallbackProcessor,
)
from openhands.app_server.event_callback.util import agent_server_error_detail
from openhands.app_server.integrations.provider import (
PROVIDER_TOKEN_TYPE,
ProviderHandler,
Expand Down Expand Up @@ -274,7 +275,13 @@ def _expected_sdk_version() -> str | None:


def _exception_detail(exc: Exception) -> str:
"""HTTPException.__str__ prepends '<status>: '; prefer its clean .detail."""
"""HTTPException.__str__ prepends '<status>: '; prefer its clean .detail.

httpx.HTTPStatusError.__str__ carries only the status and URL; prefer the
agent server's response body so the real cause reaches the caller.
"""
if isinstance(exc, httpx.HTTPStatusError):
return agent_server_error_detail(exc)
detail = getattr(exc, 'detail', None)
if isinstance(detail, dict) and isinstance(detail.get('message'), str):
return detail['message']
Expand Down
29 changes: 29 additions & 0 deletions openhands/app_server/event_callback/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from typing import TYPE_CHECKING
from uuid import UUID

import httpx

from openhands.app_server.sandbox.sandbox_models import (
AGENT_SERVER,
SandboxInfo,
Expand Down Expand Up @@ -59,3 +61,30 @@ def get_agent_server_url_from_sandbox(sandbox: SandboxInfo) -> str:
) from None

return replace_localhost_hostname_for_docker(agent_server_url)


def agent_server_error_detail(exc: httpx.HTTPStatusError) -> str:
"""Return a readable message for an agent server error response.

``str(exc)`` only carries the status and URL. The agent server puts the
real cause in ``exception`` (unhandled errors, tagged with ``error_id``)
or ``detail`` (HTTPException).
"""
try:
data = exc.response.json()
except ValueError:
data = None
message = None
error_id = None
if isinstance(data, dict):
message = data.get('exception') or data.get('detail')
if isinstance(message, dict):
message = message.get('message')
error_id = data.get('error_id')
status = exc.response.status_code
if not isinstance(message, str) or not message:
return f'Agent server error: HTTP {status}'
suffix = f'HTTP {status}'
if error_id:
suffix += f', error_id={error_id}'
return f'{message} ({suffix})'
58 changes: 58 additions & 0 deletions tests/unit/app_server/test_live_status_app_conversation_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from unittest.mock import AsyncMock, Mock, patch
from uuid import uuid4

import httpx
import pytest
from fastapi import HTTPException
from pydantic import SecretStr, ValidationError
Expand Down Expand Up @@ -4048,6 +4049,52 @@ async def test_start_app_conversation_reports_error_when_no_spec_is_available(
assert tasks[-1].status == AppConversationStartTaskStatus.ERROR
assert tasks[-1].detail == 'No sandbox specs available!'

@patch(
'openhands.app_server.app_conversation.live_status_app_conversation_service.is_custom_sandbox_spec',
return_value=False,
)
@patch(
'openhands.app_server.app_conversation.live_status_app_conversation_service.AsyncRemoteWorkspace'
)
@patch(
'openhands.app_server.app_conversation.live_status_app_conversation_service.ConversationInfo'
)
async def test_start_app_conversation_reports_agent_server_error_body(
self,
mock_conversation_info_class,
mock_remote_workspace_class,
_mock_is_custom_sandbox_spec,
):
"""A create rejected by the agent server fails the start task with the
response body's message, not just the HTTP status and URL."""
self._arrange_start_app_conversation(
uuid4(), mock_conversation_info_class, mock_remote_workspace_class
)
request = httpx.Request('POST', 'http://agent-server:8000/api/conversations')
self.mock_httpx_client.post = AsyncMock(
return_value=httpx.Response(
500,
request=request,
json={
'detail': 'Internal Server Error',
'exception': 'Unsupported or missing $schema in plugin.json',
'error_id': 'abc123',
},
)
)

tasks = [
task
async for task in self.service._start_app_conversation(
AppConversationStartRequest(title='Broken plugin')
)
]

assert tasks[-1].status == AppConversationStartTaskStatus.ERROR
assert tasks[-1].detail == (
'Unsupported or missing $schema in plugin.json (HTTP 500, error_id=abc123)'
)

@patch(
'openhands.app_server.app_conversation.live_status_app_conversation_service.AsyncRemoteWorkspace'
)
Expand Down Expand Up @@ -7278,6 +7325,17 @@ def test_exception_detail_unwraps_dict_message():
assert _exception_detail(exc) == 'Daily sandbox limit of 3 reached.'


def test_exception_detail_without_agent_server_body_omits_url():
"""An agent server error with no readable body reports the status, not
httpx's message with the sandbox URL."""
request = httpx.Request('POST', 'http://agent-server:8000/api/conversations')
response = httpx.Response(502, request=request, text='<html>Bad Gateway</html>')
with pytest.raises(httpx.HTTPStatusError) as exc_info:
response.raise_for_status()

assert _exception_detail(exc_info.value) == 'Agent server error: HTTP 502'


class TestACPProviderAllowlistAtServiceStart:
"""The allowlist is enforced in the shared start path, not only in the HTTP
endpoints. The integrations (GitHub, GitLab, Jira, Slack, ...) call
Expand Down
124 changes: 124 additions & 0 deletions tests/unit/integrations/slack/test_slack_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@

from unittest.mock import AsyncMock, MagicMock, patch

import httpx
import pytest
from jinja2 import DictLoader, Environment

from integrations.slack.slack_types import StartingConvoException
from integrations.slack.slack_view import (
SlackNewConversationView,
SlackUpdateExistingConversationView,
)
from openhands.app_server.app_conversation.app_conversation_models import (
AppConversationStartRequest,
AppConversationStartTask,
AppConversationStartTaskStatus,
)
from openhands.app_server.sandbox.sandbox_models import SandboxStatus
from openhands.app_server.user_auth.user_auth import UserAuth
from storage.slack_conversation import SlackConversation
Expand Down Expand Up @@ -170,6 +177,46 @@ async def test_v1_conversation_creation(
assert result == slack_new_conversation_view.conversation_id
mock_create_v1.assert_called_once()

@patch('integrations.slack.slack_view.get_app_conversation_service')
@patch.object(SlackNewConversationView, '_get_instructions', new_callable=AsyncMock)
async def test_v1_conversation_start_error_surfaces_task_detail(
self,
mock_get_instructions,
mock_get_app_conversation_service,
slack_new_conversation_view,
mock_jinja_env,
):
"""A failed start raises the user-facing exception with the task detail."""
# Arrange
mock_get_instructions.return_value = ('Hello OpenHands!', '')
detail = (
'Unsupported or missing $schema in plugin.json (HTTP 500, error_id=abc123)'
)
error_task = AppConversationStartTask(
created_by_user_id='test-user-123',
request=AppConversationStartRequest(),
status=AppConversationStartTaskStatus.ERROR,
detail=detail,
)

async def start_app_conversation(_request):
yield error_task

mock_service = MagicMock()
mock_service.start_app_conversation = start_app_conversation
mock_get_app_conversation_service.return_value.__aenter__.return_value = (
mock_service
)

# Act
with pytest.raises(StartingConvoException) as exc_info:
await slack_new_conversation_view.create_or_update_conversation(
mock_jinja_env
)

# Assert
assert str(exc_info.value) == f'Failed to start the conversation: {detail}'


# ---------------------------------------------------------------------------
# Test: Message Routing to V1
Expand Down Expand Up @@ -293,3 +340,80 @@ async def test_paused_sandbox_resumption(
mock_sandbox_service.resume_sandbox.assert_called_once_with('sandbox-123')
mock_httpx_client.post.assert_called_once()
mock_response.raise_for_status.assert_called_once()


# ---------------------------------------------------------------------------
# Test: Agent server errors on follow-up messages
# ---------------------------------------------------------------------------


class TestV1SendMessageFailure:
"""Test that agent server error responses reach the user on follow-ups."""

@patch('openhands.app_server.config.get_sandbox_service')
@patch('openhands.app_server.config.get_app_conversation_info_service')
@patch('openhands.app_server.config.get_httpx_client')
@patch('openhands.app_server.event_callback.util.get_agent_server_url_from_sandbox')
@patch.object(
SlackUpdateExistingConversationView, '_get_instructions', new_callable=AsyncMock
)
async def test_agent_server_error_response_surfaces_its_message(
self,
mock_get_instructions,
mock_get_agent_server_url,
mock_get_httpx_client,
mock_get_app_info_service,
mock_get_sandbox_service,
slack_update_conversation_view_v1,
mock_jinja_env,
):
"""An HTTP error from the agent server surfaces the response body."""
# Arrange
mock_get_instructions.return_value = ('Follow up message', '')
mock_get_agent_server_url.return_value = 'http://localhost:8000'

mock_app_info_service = AsyncMock()
mock_app_info_service.get_app_conversation_info.return_value = MagicMock(
sandbox_id='sandbox-123'
)
mock_get_app_info_service.return_value.__aenter__.return_value = (
mock_app_info_service
)

mock_running_sandbox = MagicMock(
status=SandboxStatus.RUNNING, session_api_key='test-api-key'
)
mock_sandbox_service = AsyncMock()
mock_sandbox_service.get_sandbox.return_value = mock_running_sandbox
mock_sandbox_service.wait_for_sandbox_running.return_value = (
mock_running_sandbox
)
mock_get_sandbox_service.return_value.__aenter__.return_value = (
mock_sandbox_service
)

request = httpx.Request('POST', 'http://localhost:8000/api/conversations')
error_response = httpx.Response(
500,
request=request,
json={
'detail': 'Internal Server Error',
'exception': 'Unsupported or missing $schema in plugin.json',
'error_id': 'abc123',
},
)
mock_httpx_client = AsyncMock()
mock_httpx_client.post.return_value = error_response
mock_get_httpx_client.return_value.__aenter__.return_value = mock_httpx_client

# Act
with pytest.raises(StartingConvoException) as exc_info:
await slack_update_conversation_view_v1.send_message_to_v1_conversation(
mock_jinja_env
)

# Assert
assert str(exc_info.value) == (
'Failed to send your message to the conversation: '
'Unsupported or missing $schema in plugin.json (HTTP 500, error_id=abc123)'
)
32 changes: 32 additions & 0 deletions tests/unit/test_slack_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
SLACK_USER_MSG_KEY_PREFIX,
SlackManager,
)
from integrations.slack.slack_types import StartingConvoException
from integrations.slack.slack_view import SlackNewConversationView
from openhands.app_server.integrations.service_types import (
ProviderTimeoutError,
Expand Down Expand Up @@ -1419,3 +1420,34 @@ async def test_link_records_the_slack_workspace(
assert link.team_id == 'T1'
assert link.org_id == user.current_org_id
assert team.team_id == 'T1'


class TestStartJobErrorMessages:
"""Start failures are relayed to the Slack user instead of a generic error."""

@patch.object(SlackManager, 'send_message', new_callable=AsyncMock)
@patch.object(
SlackNewConversationView,
'create_or_update_conversation',
new_callable=AsyncMock,
)
async def test_start_job_posts_conversation_start_failure_detail(
self,
mock_create_or_update_conversation,
mock_send_message,
slack_manager,
slack_new_conversation_view,
):
"""A StartingConvoException message is posted instead of the generic error."""
# Arrange
message = (
'Failed to start the conversation: '
'Unsupported or missing $schema in plugin.json (HTTP 500, error_id=abc123)'
)
mock_create_or_update_conversation.side_effect = StartingConvoException(message)

# Act
await slack_manager.start_job(slack_new_conversation_view)

# Assert
mock_send_message.assert_awaited_once_with(message, slack_new_conversation_view)
Loading