From 437b719d70d27a575e33b8c3c8a2cf482ce1686b Mon Sep 17 00:00:00 2001 From: hieptl Date: Mon, 26 Oct 2026 15:04:42 +0700 Subject: [PATCH] fix(slack): show the agent server's error when a conversation fails to start (OHE-3564) When the agent server rejects a Slack-triggered conversation, for example because a marketplace plugin's plugin.json lacks $schema and the plugin fails to load, the Slack user only saw "Uh oh! There was an unexpected error starting the job :(". The response body, which names the cause and carries an error_id, was dropped on the way: the app server stored httpx's status-and-URL string as the start task detail, and the Slack views raised a plain RuntimeError for a failed start or a fixed Exception for a rejected follow-up message, so start_job fell through to its catch-all in both cases. - Add agent_server_error_detail, which reads the agent server's `exception` or `detail` field plus `error_id` and falls back to the HTTP status alone, so the sandbox URL is never shown. - Route httpx.HTTPStatusError through it in _exception_detail so a rejected create reports the body's message in the start task detail. - Raise StartingConvoException with that detail in the Slack views for a failed start and for a rejected follow-up message; start_job already posts that message in the thread. --- integrations/slack/slack_view.py | 21 ++- .../live_status_app_conversation_service.py | 9 +- openhands/app_server/event_callback/util.py | 29 ++++ ...st_live_status_app_conversation_service.py | 58 ++++++++ .../integrations/slack/test_slack_view.py | 124 ++++++++++++++++++ tests/unit/test_slack_integration.py | 32 +++++ 6 files changed, 270 insertions(+), 3 deletions(-) diff --git a/integrations/slack/slack_view.py b/integrations/slack/slack_view.py index 68206ef2d3..17c40ad45c 100644 --- a/integrations/slack/slack_view.py +++ b/integrations/slack/slack_view.py @@ -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 @@ -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 @@ -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}') @@ -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, ) @@ -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', diff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.py index dba84c5e38..1077fa92fb 100644 --- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py +++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py @@ -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, @@ -274,7 +275,13 @@ def _expected_sdk_version() -> str | None: def _exception_detail(exc: Exception) -> str: - """HTTPException.__str__ prepends ': '; prefer its clean .detail.""" + """HTTPException.__str__ prepends ': '; 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'] diff --git a/openhands/app_server/event_callback/util.py b/openhands/app_server/event_callback/util.py index c4df9d87ca..eb1d506834 100644 --- a/openhands/app_server/event_callback/util.py +++ b/openhands/app_server/event_callback/util.py @@ -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, @@ -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})' diff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.py index 585c0f8940..7f91e1dd9c 100644 --- a/tests/unit/app_server/test_live_status_app_conversation_service.py +++ b/tests/unit/app_server/test_live_status_app_conversation_service.py @@ -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 @@ -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' ) @@ -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='Bad Gateway') + 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 diff --git a/tests/unit/integrations/slack/test_slack_view.py b/tests/unit/integrations/slack/test_slack_view.py index e8bc7a4cf7..62a369a768 100644 --- a/tests/unit/integrations/slack/test_slack_view.py +++ b/tests/unit/integrations/slack/test_slack_view.py @@ -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 @@ -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 @@ -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)' + ) diff --git a/tests/unit/test_slack_integration.py b/tests/unit/test_slack_integration.py index 015d85de49..fe9d259788 100644 --- a/tests/unit/test_slack_integration.py +++ b/tests/unit/test_slack_integration.py @@ -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, @@ -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)