From 6a39a25a7adbef46378c0aa60e4b439083820d9b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:03:23 +0000 Subject: [PATCH] Use a typed ServiceInactive exception instead of the "inactive_service" string ConversationService and EventService raised ValueError("inactive_service") in 52 places when used outside their running lifetime, and two event routes told it apart from bad requests by comparing str(exc). ServiceInactive replaces the string. It stays a ValueError with the same message, so REST answers and error classification do not change; the routes now catch the type. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013ArwwLYPA4zfbsUTU75ee4 --- .../agent_server/conversation_router.py | 2 +- .../agent_server/conversation_service.py | 37 +++--- .../openhands/agent_server/event_router.py | 10 +- .../openhands/agent_server/event_service.py | 106 ++++++++++-------- tests/agent_server/test_ask_user_router.py | 21 ++++ .../test_conversation_response.py | 6 +- .../agent_server/test_conversation_router.py | 8 +- .../agent_server/test_conversation_service.py | 10 +- tests/agent_server/test_event_service.py | 30 ++--- tests/agent_server/test_event_socket_races.py | 4 +- tests/agent_server/test_reactions_router.py | 19 ++++ 11 files changed, 157 insertions(+), 96 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/conversation_router.py b/openhands-agent-server/openhands/agent_server/conversation_router.py index eed19fa46dc..2289e4b66a7 100644 --- a/openhands-agent-server/openhands/agent_server/conversation_router.py +++ b/openhands-agent-server/openhands/agent_server/conversation_router.py @@ -954,7 +954,7 @@ async def navigate_conversation( ) except ValueError as exc: # An unknown ``event_id`` against an existing conversation is a 404; - # other ValueErrors (e.g. inactive_service) are genuine server errors. + # other ValueErrors (e.g. ServiceInactive) are genuine server errors. if "event_id" in str(exc): raise NotFound(str(exc)) from exc raise diff --git a/openhands-agent-server/openhands/agent_server/conversation_service.py b/openhands-agent-server/openhands/agent_server/conversation_service.py index 4cc2ba06cac..6942f67ac2c 100644 --- a/openhands-agent-server/openhands/agent_server/conversation_service.py +++ b/openhands-agent-server/openhands/agent_server/conversation_service.py @@ -24,6 +24,7 @@ LEASE_RENEW_INTERVAL_SECONDS, EventService, RunSlot, + ServiceInactive, ) from openhands.agent_server.experimental_features import ( experimental_feature_tools, @@ -779,7 +780,7 @@ async def prepare_for_sandbox_pause(self) -> None: async with self._exclusive_lifecycle(): event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() active_services = tuple(event_services.items()) results = await asyncio.gather( *( @@ -890,7 +891,7 @@ async def _conversation_info( ) -> ConversationInfo | None: event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() children = ( children_index.get(conversation_id, []) @@ -1000,7 +1001,7 @@ async def _refresh_execution_statuses(self) -> None: """ event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() targets: list[tuple[UUID, str, tuple[int, int] | None]] = [] for conversation_id, record in list(self._conversation_records.items()): @@ -1049,7 +1050,7 @@ async def refresh_persisted_conversation(self, conversation_id: UUID) -> None: """Refresh one catalog record changed by an external runtime.""" event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() disk_records = await asyncio.to_thread(self._load_catalog_sync, conversation_id) if conversation_id not in disk_records: event_service = event_services.get(conversation_id) @@ -1069,7 +1070,7 @@ async def _reconcile_active_records(self) -> None: """Add injected live services to the in-memory catalog.""" event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() for conversation_id, event_service in event_services.items(): if conversation_id in self._conversation_records: continue @@ -1151,7 +1152,7 @@ async def _get_or_load_event_service( ) -> EventService | None: event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() if ( conversation_id not in event_services and conversation_id not in self._conversation_records @@ -1169,7 +1170,7 @@ async def _get_or_load_event_service_locked( ) -> EventService | None: event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() event_service = event_services.get(conversation_id) if event_service is not None and event_service.is_open(): @@ -1204,7 +1205,7 @@ async def _get_or_load_event_service_locked( async def get_conversation(self, conversation_id: UUID) -> ConversationInfo | None: if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() record = self._conversation_records.get(conversation_id) if record is None: event_service = self._event_services.get(conversation_id) @@ -1270,7 +1271,7 @@ async def _search_conversations( sort_order: ConversationSortOrder, ) -> tuple[list[ConversationInfo], str | None]: if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() await self._reconcile_active_records() if execution_status is not None: @@ -1333,7 +1334,7 @@ async def _count_conversations( ) -> int: """Count conversations matching the given filters.""" if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() await self._reconcile_active_records() if execution_status is None: @@ -1429,7 +1430,7 @@ async def _reuse_existing_conversation_locked( catalog cannot change between the existence check and the reuse. """ if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() existing_record = self._conversation_records.get(conversation_id) existing_event_service = self._event_services.get(conversation_id) stored = ( @@ -1576,7 +1577,7 @@ async def _start_conversation( ) -> tuple[ConversationInfo, bool]: """Start a local event_service and return its id.""" if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() conversation_id = request.conversation_id or uuid4() if self._has_conversation(conversation_id): async with self._conversation_lifecycle(conversation_id): @@ -1915,7 +1916,7 @@ def _worktree_dir(self, stored: StoredConversation) -> Path | None: async def delete_conversation(self, conversation_id: UUID) -> bool: event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() if ( conversation_id not in event_services and conversation_id not in self._conversation_records @@ -2056,7 +2057,7 @@ async def get_persisted_event_service( ) -> EventService | None: """Open append-only event history without acquiring a runtime lease.""" if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() record = self._conversation_records.get(conversation_id) if record is None: return None @@ -2121,7 +2122,7 @@ async def fork_conversation( conversation. """ if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() # Reject duplicate fork IDs before fork() writes into its persistence # directory. The catalog includes both live and unloaded conversations. @@ -2222,7 +2223,7 @@ async def start_child_conversation( Nothing is persisted in that case. """ if self._event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() parent_service = await self._get_or_load_event_service(parent_id) if parent_service is None: @@ -2572,7 +2573,7 @@ async def _start_event_service( ) -> EventService: event_services = self._event_services if event_services is None: - raise ValueError("inactive_service") + raise ServiceInactive() # A new conversation starts with the ``launched`` agent (meta.json does # not carry it). Otherwise the agent is read from base_state.json, and @@ -2639,7 +2640,7 @@ async def _start_event_service( # even if the system is not shut down gracefully await event_service.save_meta() if self._event_services is not event_services: - raise ValueError("inactive_service") + raise ServiceInactive() state = await event_service.get_state() except BaseException: try: diff --git a/openhands-agent-server/openhands/agent_server/event_router.py b/openhands-agent-server/openhands/agent_server/event_router.py index 99c4fa32bbb..b14f639e9c4 100644 --- a/openhands-agent-server/openhands/agent_server/event_router.py +++ b/openhands-agent-server/openhands/agent_server/event_router.py @@ -25,7 +25,7 @@ get_settings_store, ) from openhands.agent_server.errors import error_responses -from openhands.agent_server.event_service import EventService +from openhands.agent_server.event_service import EventService, ServiceInactive from openhands.agent_server.experimental_features import ( host_experimental_features, is_enabled, @@ -451,9 +451,9 @@ async def react_to_message( return await event_service.react( request.emoji, request.target_event_id, removed=request.removed ) + except ServiceInactive: + raise except ValueError as exc: - if str(exc) == "inactive_service": - raise raise Invalid(str(exc)) @@ -498,9 +498,9 @@ async def answer_ask_user( return await event_service.answer_ask( request.ask_id, request.option_index, request.text ) + except ServiceInactive: + raise except ValueError as exc: - if str(exc) == "inactive_service": - raise raise Invalid(str(exc)) diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index e16a3d111e1..f1a6ef3c0fb 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -142,6 +142,17 @@ class CondensationUnavailable(ValueError): """The conversation's agent has no condenser that handles requests.""" +class ServiceInactive(ValueError): + """The service is not running: not started yet, or closing or closed. + + It stays a ``ValueError`` with the message ``"inactive_service"``, so + routes and clients see the same error as before; callers catch the type. + """ + + def __init__(self) -> None: + super().__init__("inactive_service") + + class _RunPermit: """Ref-counted permit shared by the chained runs of one admission session.""" @@ -494,7 +505,7 @@ async def apply_resume_secrets( ) -> None: conversation = self._conversation if conversation is None: - raise ValueError("inactive_service") + raise ServiceInactive() secrets = { name: value for name, value in secrets.items() @@ -562,7 +573,7 @@ async def _renew_lease_loop(self) -> None: def get_conversation(self): if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() return self._conversation @classmethod @@ -581,7 +592,7 @@ def _events_for_read(self) -> EventLog: if self._persisted_events is not None: return self._persisted_events if self._conversation is None: - raise ValueError("inactive_service") + raise ServiceInactive() return self._conversation._state.events def _get_event_sync(self, event_id: str) -> Event | None: @@ -818,7 +829,7 @@ async def count_events( def _get_execution_status_sync(self) -> ConversationExecutionStatus: if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() with self._conversation._state as state: return state.execution_status @@ -867,7 +878,7 @@ def _publish_error_event_sync(self, exc: BaseException) -> None: def _create_state_update_event_sync(self) -> ConversationStateUpdateEvent: if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() state = self._conversation._state with state: event = ConversationStateUpdateEvent.from_conversation_state(state) @@ -877,7 +888,7 @@ def _create_initial_state_sync( self, ) -> tuple[ConversationStateUpdateEvent, int]: if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() state = self._conversation._state with state: return self._create_state_update_event_sync(), len(state.events) @@ -944,7 +955,7 @@ async def send_message( run_slot: RunSlot | None = None, ): if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() # A normal user message supersedes any active /goal loop in this # conversation. The goal loop's own messages pass _from_goal_loop=True. if not _from_goal_loop: @@ -993,7 +1004,7 @@ async def send_message( # the request — rather than inferring it later from an IDLE # status — is what keeps a deliberate run=False append, or an # IDLE reached via another path, from triggering an unwanted - # run. "inactive_service" is terminal and must not re-arm. + # run. ServiceInactive is terminal and must not re-arm. if ( str(e) == "conversation_already_running" and not active_acp_prompt_has_latest_message @@ -1613,11 +1624,12 @@ async def run( in the thread pool as before. Raises: - ValueError: If the service is inactive or conversation is already running. + ServiceInactive: If the service is inactive. + ValueError: If the conversation is already running. ConversationRunLimitExceeded: If all server run slots are occupied. """ if not self._conversation or self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() request_generation = self._explicit_interrupt_generation # Use lock to make check-and-set atomic, preventing race conditions @@ -1639,7 +1651,7 @@ async def run( ): raise ValueError("conversation_already_running") if self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() # Re-check: the status read above can yield to a late stop too. if ( acp_internal_rerun_generation is not None @@ -1878,11 +1890,12 @@ async def start_goal_loop( max_iterations: Hard cap on audit rounds before giving up. Raises: - ValueError: If the service is inactive, a goal loop is already - running, no judge LLM is available, or the objective is empty. + ServiceInactive: If the service is inactive. + ValueError: If a goal loop is already running, no judge LLM is + available, or the objective is empty. """ if not self._conversation or self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() if judge_llm is None: judge_llm = getattr(self._conversation.agent, "llm", None) if judge_llm is None: @@ -1893,7 +1906,7 @@ async def start_goal_loop( # conversation run; otherwise /goal could judge an unrelated transcript. async with self._run_lock: if self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() if self._goal_loop_task is not None and not self._goal_loop_task.done(): raise ValueError("goal_already_running") # _run_task first: a live run holds the state lock across its step, @@ -1907,7 +1920,7 @@ async def start_goal_loop( # it may have begun teardown meanwhile (mirrors run()'s post-status # _closing re-check) -- avoid spawning a task close() won't cancel. if self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() self._goal_loop_outcome = None await self._schedule_goal_loop(controller) @@ -1923,7 +1936,7 @@ def _require_answered() -> None: await asyncio.get_running_loop().run_in_executor(None, _require_answered) if self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() # Reserve capacity before spawning the loop so a full server refuses # /goal with 429 up front (matching /run), rather than admitting the # request and failing mid-loop. @@ -2141,13 +2154,14 @@ async def resume_goal_loop( and across a server restart because goal-status events are persisted. Raises: - ValueError: If the service is inactive, a goal loop is already - running, no judge LLM is available, or there is no resumable goal - loop because none was started or it already completed/capped, - or an ask_user question still awaits the user's answer. + ServiceInactive: If the service is inactive. + ValueError: If a goal loop is already running, no judge LLM is + available, there is no resumable goal loop because none was + started or it already completed/capped, or an ask_user + question still awaits the user's answer. """ if not self._conversation or self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() last = await loop.run_in_executor(None, self._last_goal_loop_status) if last is None or last.get("status") in ("complete", "capped"): @@ -2171,7 +2185,7 @@ async def resume_goal_loop( # Same busy guard as start_goal_loop: refuse a goal loop or active run. async with self._run_lock: if self._closing: - raise ValueError("inactive_service") + raise ServiceInactive() if self._goal_loop_task is not None and not self._goal_loop_task.done(): raise ValueError("goal_already_running") if (self._run_task is not None and not self._run_task.done()) or ( @@ -2180,7 +2194,7 @@ async def resume_goal_loop( ): raise ValueError("conversation_already_running") if self._closing: # see start_goal_loop: close() may have begun teardown - raise ValueError("inactive_service") + raise ServiceInactive() self._goal_loop_outcome = None await self._schedule_goal_loop(controller, resume=True) @@ -2212,7 +2226,7 @@ async def react( ValueError: The emoji is not allowed or there is no such message. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() conversation = self._conversation loop = asyncio.get_running_loop() return await loop.run_in_executor( @@ -2232,7 +2246,7 @@ async def answer_ask( ValueError: The question is not pending, or the answer is invalid. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() answer, message = await loop.run_in_executor( None, @@ -2244,7 +2258,7 @@ async def answer_ask( async def reject_pending_actions(self, reason: str): """Reject all pending actions and publish updated state.""" if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor( None, self._conversation.reject_pending_actions, reason @@ -2291,7 +2305,7 @@ async def interrupt(self, *, internal_acp_rerun: bool = False): async def add_mcp_servers(self, servers: dict[str, MCPServer]) -> None: """Add modern MCP servers to the conversation.""" if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._conversation.add_mcp_servers, servers) await self._publish_state_update() @@ -2299,7 +2313,7 @@ async def add_mcp_servers(self, servers: dict[str, MCPServer]) -> None: async def update_secrets(self, secrets: dict[str, SecretValue]): """Update secrets in the conversation.""" if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() profile = self.stored.launched_agent_profile if profile is not None: secrets = { @@ -2316,7 +2330,7 @@ async def update_secrets(self, secrets: dict[str, SecretValue]): async def set_confirmation_policy(self, policy: ConfirmationPolicyBase): """Set the confirmation policy for the conversation.""" if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor( None, self._conversation.set_confirmation_policy, policy @@ -2331,7 +2345,7 @@ async def set_max_budget_per_run(self, max_budget_per_run: float | None) -> None """ conversation = self._conversation if conversation is None: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor( None, setattr, conversation, "max_budget_per_run", max_budget_per_run @@ -2342,7 +2356,7 @@ async def set_security_analyzer( ): """Set the security analyzer for the conversation.""" if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor( None, self._conversation.set_security_analyzer, security_analyzer @@ -2351,7 +2365,7 @@ async def set_security_analyzer( async def load_plugin(self, plugin_ref: str) -> None: """Load a marketplace plugin into the active conversation.""" if self._conversation is None: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._conversation.load_plugin, plugin_ref) @@ -2369,11 +2383,11 @@ async def switch_acp_model(self, model: str) -> None: needed. """ if self._conversation is None: - # Match the inactive-service convention of the other event-service - # methods (the conversation router maps it to 400). The SDK no - # longer raises for a created-but-not-yet-run conversation, so a - # pre-first-run switch is a normal 200 deferral, not an error. - raise ValueError("inactive_service") + # Inactive, as in the other event-service methods (the + # conversation router maps it to 400). The SDK no longer raises for + # a created-but-not-yet-run conversation, so a pre-first-run switch + # is a normal 200 deferral, not an error. + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._conversation.switch_acp_model, model) @@ -2384,7 +2398,7 @@ async def switch_acp_effort(self, effort: str) -> None: worker thread, a not-yet-run conversation only persists the value. """ if self._conversation is None: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._conversation.switch_acp_effort, effort) @@ -2471,7 +2485,7 @@ async def generate_title( executor to avoid blocking the event loop. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() resolved_llm = llm if llm is not None: @@ -2493,7 +2507,7 @@ async def ask_agent(self, question: str) -> str: Delegates to LocalConversation in an executor to avoid blocking the event loop. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() return await loop.run_in_executor(None, self._conversation.ask_agent, question) @@ -2504,7 +2518,7 @@ async def condense(self) -> None: Delegates to LocalConversation in an executor to avoid blocking the event loop. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() # A missing or request-ignoring condenser is the caller's agent # configuration, not a server fault: report it as such instead of @@ -2532,7 +2546,7 @@ async def navigate_to(self, event_id: str | None) -> None: ValueError: If ``event_id`` is not ``None`` and not in the conversation. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() return await loop.run_in_executor( @@ -2549,7 +2563,7 @@ def _get_agent_final_response_sync(self) -> str: append-only and immutable once written. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() return get_agent_final_response(self._conversation._state.active_branch()) async def get_agent_final_response(self) -> str: @@ -2559,13 +2573,13 @@ async def get_agent_final_response(self) -> str: or empty string if no final response is found. """ if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() loop = asyncio.get_running_loop() return await loop.run_in_executor(None, self._get_agent_final_response_sync) async def get_state(self) -> ConversationState: if not self._conversation: - raise ValueError("inactive_service") + raise ServiceInactive() return self._conversation._state async def _publish_to_subscribers(self, event: Event) -> None: diff --git a/tests/agent_server/test_ask_user_router.py b/tests/agent_server/test_ask_user_router.py index 634d3a94366..cb3d90d821b 100644 --- a/tests/agent_server/test_ask_user_router.py +++ b/tests/agent_server/test_ask_user_router.py @@ -21,6 +21,7 @@ get_settings_store, ) from openhands.agent_server.event_router import event_router +from openhands.agent_server.event_service import ServiceInactive from openhands.agent_server.models import StartConversationRequest from openhands.agent_server.persistence import PersistedSettings, ServerStores from openhands.sdk import LLM, Agent @@ -218,3 +219,23 @@ async def test_answers_are_refused_while_the_feature_is_off( assert response.status_code == 409 assert find_pending_ask(await _events(service, cid)) is not None + + +@pytest.mark.asyncio +async def test_an_inactive_service_is_not_a_bad_answer(client, service, tmp_path): + """ServiceInactive is a server state, not a bad request: it is not a 400.""" + cid, ask_id = await _conversation_with_question(service, tmp_path) + event_service = await service.get_event_service(cid) + assert event_service is not None + + async def inactive(*args, **kwargs): + raise ServiceInactive() + + with ( + patch.object(event_service, "answer_ask", inactive), + pytest.raises(ServiceInactive), + ): + await client.post( + f"/api/conversations/{cid}/ask_user/answer", + json={"ask_id": ask_id, "option_index": 0}, + ) diff --git a/tests/agent_server/test_conversation_response.py b/tests/agent_server/test_conversation_response.py index 7b543e45b14..47a94f436ac 100644 --- a/tests/agent_server/test_conversation_response.py +++ b/tests/agent_server/test_conversation_response.py @@ -14,7 +14,7 @@ from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.dependencies import get_conversation_service -from openhands.agent_server.event_service import EventService +from openhands.agent_server.event_service import EventService, ServiceInactive from openhands.sdk import LLM, Agent, Conversation, LocalConversation, Message from openhands.sdk.event import ActionEvent, MessageEvent from openhands.sdk.llm import MessageToolCall, TextContent @@ -180,10 +180,10 @@ def test_event_service_get_agent_final_response_empty(): def test_event_service_get_agent_final_response_inactive(): - """EventService raises ValueError when service is inactive.""" + """EventService raises ServiceInactive when the service is inactive.""" event_service = EventService(stored=MagicMock(), conversations_dir=Path("test_dir")) - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): event_service._get_agent_final_response_sync() diff --git a/tests/agent_server/test_conversation_router.py b/tests/agent_server/test_conversation_router.py index 1846e4d4b3e..9823cec7462 100644 --- a/tests/agent_server/test_conversation_router.py +++ b/tests/agent_server/test_conversation_router.py @@ -15,7 +15,11 @@ from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.dependencies import get_conversation_service -from openhands.agent_server.event_service import CondensationUnavailable, EventService +from openhands.agent_server.event_service import ( + CondensationUnavailable, + EventService, + ServiceInactive, +) from openhands.agent_server.launch import launch_source from openhands.agent_server.models import ( ConversationInfo, @@ -2686,7 +2690,7 @@ def test_load_conversation_plugin_inactive_service_returns_400( ): """The /load_plugin endpoint maps inactive runtime state to 400.""" mock_conversation_service.get_event_service.return_value = mock_event_service - mock_event_service.load_plugin.side_effect = ValueError("inactive_service") + mock_event_service.load_plugin.side_effect = ServiceInactive() client.app.dependency_overrides[get_conversation_service] = lambda: ( mock_conversation_service ) diff --git a/tests/agent_server/test_conversation_service.py b/tests/agent_server/test_conversation_service.py index cbf2efd9823..38daad6532a 100644 --- a/tests/agent_server/test_conversation_service.py +++ b/tests/agent_server/test_conversation_service.py @@ -28,7 +28,7 @@ _get_worktree_start_point, _plan_conversation_worktree, ) -from openhands.agent_server.event_service import EventService +from openhands.agent_server.event_service import EventService, ServiceInactive from openhands.agent_server.models import ( ConversationInfo, ConversationPage, @@ -1481,7 +1481,7 @@ async def test_search_conversations_inactive_service(self, conversation_service) """Test that search_conversations raises ValueError when service is inactive.""" conversation_service._event_services = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await conversation_service.search_conversations() @pytest.mark.asyncio @@ -1848,7 +1848,7 @@ async def test_count_conversations_inactive_service(self, conversation_service): """Test that count_conversations raises ValueError when service is inactive.""" conversation_service._event_services = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await conversation_service.count_conversations() @pytest.mark.asyncio @@ -3085,7 +3085,7 @@ async def test_update_conversation_inactive_service(self, conversation_service): conversation_service._event_services = None request = UpdateConversationRequest(title="New Title") - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await conversation_service.update_conversation(uuid4(), request) @pytest.mark.asyncio @@ -3291,7 +3291,7 @@ async def test_delete_conversation_inactive_service(self, conversation_service): """Test that delete_conversation raises ValueError when service is inactive.""" conversation_service._event_services = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await conversation_service.delete_conversation(uuid4()) @pytest.mark.asyncio diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index 92100cb3ea4..b01fab373b0 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -27,6 +27,7 @@ CondensationUnavailable, EventService, RunSlot, + ServiceInactive, _log_emit_failure, ) from openhands.agent_server.file_router import _create_zip_from_directory @@ -260,7 +261,7 @@ async def test_search_events_inactive_service(self, event_service): """Test that search_events raises ValueError when conversation is not active.""" event_service._conversation = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await event_service.search_events() @pytest.mark.asyncio @@ -743,7 +744,7 @@ async def test_count_events_inactive_service(self, event_service): """Test that count_events raises ValueError when service is inactive.""" event_service._conversation = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await event_service.count_events() @pytest.mark.asyncio @@ -877,7 +878,7 @@ async def test_send_message_inactive_service(self, event_service): event_service._conversation = None message = Message(role="user", content=[]) - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await event_service.send_message(message) @pytest.mark.asyncio @@ -1734,7 +1735,7 @@ async def test_load_plugin_inactive_service(self, event_service): """Runtime plugin loads require an active conversation.""" event_service._conversation = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await event_service.load_plugin("plugin@team") @@ -1775,7 +1776,7 @@ async def test_reject_pending_actions_inactive_service(self, event_service): """Rejecting pending actions should fail when service is inactive.""" event_service._conversation = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await event_service.reject_pending_actions("any reason") @pytest.mark.asyncio @@ -2035,7 +2036,7 @@ async def test_run_inactive_service(self, event_service): """Test that run raises ValueError when conversation is not active.""" event_service._conversation = None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await event_service.run() @pytest.mark.asyncio @@ -2405,13 +2406,14 @@ async def test_switch_acp_model_persists_via_conversation(self, tmp_path): assert "agent" not in json.loads(meta_file.read_text()) @pytest.mark.asyncio - async def test_switch_acp_model_inactive_service_raises_value_error(self, tmp_path): - """An inactive service (no live conversation) raises the shared - ``inactive_service`` ValueError — consistent with the other - event-service methods — which the router maps to 400. It is no longer a - RuntimeError: the SDK now defers (rather than rejects) a switch before - the first run(), so the only failure mode here is a closed/never-started - service. + async def test_switch_acp_model_inactive_service_raises_service_inactive( + self, tmp_path + ): + """An inactive service (no live conversation) raises ServiceInactive, + like the other event-service methods, which the router maps to 400. + It is no longer a RuntimeError: the SDK now defers (rather than + rejects) a switch before the first run(), so the only failure mode + here is a closed/never-started service. """ stored = StoredConversation( @@ -2425,7 +2427,7 @@ async def test_switch_acp_model_inactive_service_raises_value_error(self, tmp_pa # _conversation defaults to None (service not started). assert service._conversation is None - with pytest.raises(ValueError, match="inactive_service"): + with pytest.raises(ServiceInactive): await service.switch_acp_model("new-model") diff --git a/tests/agent_server/test_event_socket_races.py b/tests/agent_server/test_event_socket_races.py index 519fda5427e..43e29703f80 100644 --- a/tests/agent_server/test_event_socket_races.py +++ b/tests/agent_server/test_event_socket_races.py @@ -13,7 +13,7 @@ from openhands.agent_server import session_socket, sockets from openhands.agent_server.config import Config -from openhands.agent_server.event_service import EventService +from openhands.agent_server.event_service import EventService, ServiceInactive from openhands.agent_server.models import StoredConversation from openhands.agent_server.pub_sub import PubSub, Subscriber from openhands.agent_server.server_context import build_server_context @@ -241,7 +241,7 @@ async def test_failed_subscribe_releases_its_slot(svc, monkeypatch): baseline = svc._pub_sub.subscriber_ids() def boom(): - raise ValueError("inactive_service") + raise ServiceInactive() monkeypatch.setattr(svc, "_create_initial_state_sync", boom) ws = _FakeWS() diff --git a/tests/agent_server/test_reactions_router.py b/tests/agent_server/test_reactions_router.py index 17249d93176..4db9e63e340 100644 --- a/tests/agent_server/test_reactions_router.py +++ b/tests/agent_server/test_reactions_router.py @@ -1,6 +1,7 @@ """Tests for POST /api/conversations/{id}/reactions.""" from collections.abc import AsyncIterator +from unittest.mock import patch from uuid import UUID import httpx @@ -14,6 +15,7 @@ get_settings_store, ) from openhands.agent_server.event_router import event_router +from openhands.agent_server.event_service import ServiceInactive from openhands.agent_server.experimental_features import ( RUNTIME_EXPERIMENTAL_FEATURES_ENV, ) @@ -162,3 +164,20 @@ async def test_a_docker_runtime_leaves_the_switch_to_its_host( ) assert response.status_code == 200, response.text + + +@pytest.mark.asyncio +async def test_an_inactive_service_is_not_a_bad_reaction(client, service, tmp_path): + """ServiceInactive is a server state, not a bad request: it is not a 400.""" + cid, _ = await _conversation_with_answer(service, tmp_path) + event_service = await service.get_event_service(cid) + assert event_service is not None + + async def inactive(*args, **kwargs): + raise ServiceInactive() + + with ( + patch.object(event_service, "react", inactive), + pytest.raises(ServiceInactive), + ): + await client.post(f"/api/conversations/{cid}/reactions", json={"emoji": "+1"})