π OpenHands: AI-Driven Development
chore: Add sdk to mypy checking and fix the resulting errors (#13637)
Ray Myers72194f19db61
diff --git a/dev_config/python/.pre-commit-config.yaml b/dev_config/python/.pre-commit-config.yamlindex bb5eb607b8..a076d6cef7 100644--- a/dev_config/python/.pre-commit-config.yaml+++ b/dev_config/python/.pre-commit-config.yaml@@ -58,6 +58,8 @@ repos:types-Markdown,pydantic,lxml,+ "openhands-sdk==1.14",+ "openhands-tools==1.14",]# To see gaps add `--html-report mypy-report/`entry: mypy --config-file dev_config/python/mypy.ini openhands/diff --git a/dev_config/python/mypy.ini b/dev_config/python/mypy.iniindex c41f425b5d..0be43bc8ce 100644--- a/dev_config/python/mypy.ini+++ b/dev_config/python/mypy.ini@@ -14,3 +14,11 @@ exclude = (third_party/|enterprise/)[mypy-openhands.memory.condenser.impl.*]disable_error_code = override++[mypy-openai.*]+follow_imports = skip+ignore_missing_imports = True++[mypy-litellm.*]+follow_imports = skip+ignore_missing_imports = Truediff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.pyindex 5a54137ddf..41b7e4e12c 100644--- a/openhands/app_server/app_conversation/app_conversation_router.py+++ b/openhands/app_server/app_conversation/app_conversation_router.py@@ -644,7 +644,7 @@ async def get_conversation_skills(skill_type = 'knowledge'# Extract triggers- triggers = []+ triggers: list[str] = []if isinstance(skill.trigger, (KeywordTrigger, TaskTrigger)):if hasattr(skill.trigger, 'keywords'):triggers = skill.trigger.keywordsdiff --git a/openhands/app_server/app_conversation/app_conversation_service_base.py b/openhands/app_server/app_conversation/app_conversation_service_base.pyindex 4f415dad53..72dfd19fcf 100644--- a/openhands/app_server/app_conversation/app_conversation_service_base.py+++ b/openhands/app_server/app_conversation/app_conversation_service_base.py@@ -5,7 +5,7 @@ import tempfilefrom abc import ABCfrom dataclasses import dataclassfrom pathlib import Path-from typing import TYPE_CHECKING, AsyncGenerator+from typing import TYPE_CHECKING, Any, AsyncGeneratorfrom uuid import UUIDif TYPE_CHECKING:@@ -412,14 +412,18 @@ class AppConversationServiceBase(AppConversationService, ABC):project_dir: Project root directory (repo root when a repo is selected)."""command = 'mkdir -p .git/hooks && chmod +x .openhands/pre-commit.sh'- result = await workspace.execute_command(command, project_dir)- if result.exit_code:+ pre_commit_command_result = await workspace.execute_command(+ command, project_dir+ )+ if pre_commit_command_result.exit_code:return# Check if there's an existing pre-commit hookwith tempfile.TemporaryFile(mode='w+t') as temp_file:- result = await workspace.file_download(PRE_COMMIT_HOOK, str(temp_file))- if result.success:+ download_result = await workspace.file_download(+ PRE_COMMIT_HOOK, str(temp_file)+ )+ if download_result.success:_logger.info('Preserving existing pre-commit hook')# an existing pre-commit hook existsif 'This hook was installed by OpenHands' not in temp_file.read():@@ -428,10 +432,12 @@ class AppConversationServiceBase(AppConversationService, ABC):f'mv {PRE_COMMIT_HOOK} {PRE_COMMIT_LOCAL} &&'f'chmod +x {PRE_COMMIT_LOCAL}')- result = await workspace.execute_command(command, project_dir)- if result.exit_code != 0:+ mv_chmod_result = await workspace.execute_command(+ command, project_dir+ )+ if mv_chmod_result.exit_code != 0:_logger.error(- f'Failed to preserve existing pre-commit hook: {result.stderr}',+ f'Failed to preserve existing pre-commit hook: {mv_chmod_result.stderr}',)return@@ -442,9 +448,11 @@ class AppConversationServiceBase(AppConversationService, ABC):)# Make the pre-commit hook executable- result = await workspace.execute_command(f'chmod +x {PRE_COMMIT_HOOK}')- if result.exit_code:- _logger.error(f'Failed to make pre-commit hook executable: {result.stderr}')+ chmod_result = await workspace.execute_command(f'chmod +x {PRE_COMMIT_HOOK}')+ if chmod_result.exit_code:+ _logger.error(+ f'Failed to make pre-commit hook executable: {chmod_result.stderr}'+ )return_logger.info('Git pre-commit hook installed successfully')@@ -466,7 +474,7 @@ class AppConversationServiceBase(AppConversationService, ABC):Configured LLMSummarizingCondenser instance"""# LLMSummarizingCondenser SDK defaults: max_size=240, keep_first=2- condenser_kwargs = {+ condenser_kwargs: dict[str, Any] = {'llm': llm.model_copy(update={'usage_id': (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.pyindex 3c2facf3be..b35d3dc03a 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@@ -324,10 +324,15 @@ class LiveStatusAppConversationService(AppConversationServiceBase):f'Sending StartConversationRequest with hook_config: 'f'{hook_config_in_request}')+ headers = (+ {'X-Session-API-Key': sandbox.session_api_key}+ if sandbox.session_api_key+ else {}+ )response = await self.httpx_client.post(f'{agent_server_url}/api/conversations',json=body_json,- headers={'X-Session-API-Key': sandbox.session_api_key},+ headers=headers,timeout=self.sandbox_startup_timeout,)@@ -875,7 +880,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):static_token = await self.user_context.get_latest_token(provider_type)if static_token:secrets[secret_name] = StaticSecret(- value=static_token, description=description+ value=SecretStr(static_token), description=description)return secrets@@ -890,7 +895,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):Returns:Configured LLM instance"""- model = llm_model or user.llm_model+ model: str = llm_model or user.llm_model or LLM.model_fields['model'].defaultbase_url = user.llm_base_urlif model and (model.startswith('openhands/') or model.startswith('litellm_proxy/')@@ -1155,7 +1160,6 @@ class LiveStatusAppConversationService(AppConversationServiceBase):system_prompt_filename='system_prompt_planning.j2',system_prompt_kwargs={'plan_structure': format_plan_structure()},condenser=condenser,- security_analyzer=None,mcp_config=mcp_config,)else:diff --git a/openhands/app_server/app_conversation/skill_loader.py b/openhands/app_server/app_conversation/skill_loader.pyindex d5976aedac..d83d9b83ee 100644--- a/openhands/app_server/app_conversation/skill_loader.py+++ b/openhands/app_server/app_conversation/skill_loader.py@@ -368,7 +368,7 @@ def _convert_skill_info_to_skill(skill_info: SkillInfo) -> Skill:Returns:Skill object"""- trigger = None+ trigger: TaskTrigger | KeywordTrigger | None = Noneif skill_info.triggers:# Determine trigger type based on contentdiff --git a/openhands/app_server/config.py b/openhands/app_server/config.pyindex 584ba8ba8e..c19e39f06e 100644--- a/openhands/app_server/config.py+++ b/openhands/app_server/config.py@@ -220,9 +220,12 @@ def config_from_env() -> AppServerConfig:config.event = AwsEventServiceInjector(bucket_name=bucket_name)elif provider == StorageProvider.GCP:# Google Cloud storage configuration- config.event = GoogleCloudEventServiceInjector(- bucket_name=os.environ.get('FILE_STORE_PATH')- )+ bucket_name = os.environ.get('FILE_STORE_PATH')+ if not bucket_name:+ raise ValueError(+ 'FILE_STORE_PATH environment variable is required for Google Cloud storage'+ )+ config.event = GoogleCloudEventServiceInjector(bucket_name=bucket_name)else:config.event = FilesystemEventServiceInjector()diff --git a/openhands/app_server/event/event_service_base.py b/openhands/app_server/event/event_service_base.pyindex afe490a115..a028a485f9 100644--- a/openhands/app_server/event/event_service_base.py+++ b/openhands/app_server/event/event_service_base.py@@ -68,7 +68,7 @@ class EventServiceBase(EventService, ABC):conversation_path = await self.get_conversation_path(conversation_id)path = conversation_path / f'{event_id.hex}.json'loop = asyncio.get_running_loop()- event: Event = await loop.run_in_executor(None, self._load_event, path)+ event: Event = await loop.run_in_executor(None, self._load_event, path) # type: ignore[arg-type]return eventasync def search_events(@@ -85,8 +85,10 @@ class EventServiceBase(EventService, ABC):loop = asyncio.get_running_loop()prefix = await self.get_conversation_path(conversation_id)paths = await loop.run_in_executor(None, self._search_paths, prefix)++ # Type error: run_in_executor expects a return value, but self._load_event is typed return Event | None.events = await asyncio.gather(- *[loop.run_in_executor(None, self._load_event, path) for path in paths]+ *[loop.run_in_executor(None, self._load_event, path) for path in paths] # type: ignore[arg-type])items = []for event in events:@@ -94,9 +96,10 @@ class EventServiceBase(EventService, ABC):continueif kind__eq and event.kind != kind__eq:continue- if timestamp__gte and event.timestamp < timestamp__gte:+ # TODO: Are these comparison operators valid?+ if timestamp__gte and event.timestamp < timestamp__gte: # type: ignore[operator]continue- if timestamp__lt and event.timestamp >= timestamp__lt:+ if timestamp__lt and event.timestamp >= timestamp__lt: # type: ignore[operator]continueitems.append(event)@@ -154,7 +157,7 @@ class EventServiceBase(EventService, ABC):if isinstance(event.id, str):id_hex = event.id.replace('-', '')else:- id_hex = event.id.hex+ id_hex = event.id.hex # type: ignore[unreachable]path = (await self.get_conversation_path(conversation_id)) / f'{id_hex}.json'loop = asyncio.get_running_loop()await loop.run_in_executor(None, self._store_event, path, event)diff --git a/openhands/app_server/event/filesystem_event_service.py b/openhands/app_server/event/filesystem_event_service.pyindex 3dcb687b4b..8675e91ba2 100644--- a/openhands/app_server/event/filesystem_event_service.py+++ b/openhands/app_server/event/filesystem_event_service.py@@ -23,8 +23,8 @@ class FilesystemEventService(EventServiceBase):def _load_event(self, path: Path) -> Event | None:try:content = path.read_text()- content = Event.model_validate_json(content)- return content+ content = Event.model_validate_json(content) # type: ignore[assignment]+ return content # type: ignore[return-value]except Exception:if path.exists():_logger.exception('Error reading event', stack_info=True)diff --git a/openhands/app_server/event_callback/set_title_callback_processor.py b/openhands/app_server/event_callback/set_title_callback_processor.pyindex 3251d048ae..7805042b92 100644--- a/openhands/app_server/event_callback/set_title_callback_processor.py+++ b/openhands/app_server/event_callback/set_title_callback_processor.py@@ -52,11 +52,16 @@ async def _poll_for_title(for _ in range(_NUM_POLL_ATTEMPTS):await asyncio.sleep(_POLL_DELAY_S)try:+ headers = (+ {+ 'X-Session-API-Key': session_api_key,+ }+ if session_api_key+ else {}+ )response = await httpx_client.get(url,- headers={- 'X-Session-API-Key': session_api_key,- },+ headers=headers,)response.raise_for_status()except httpx.HTTPError as exc:diff --git a/openhands/integrations/provider.py b/openhands/integrations/provider.pyindex 695f0a6ad6..7a8cc2db43 100644--- a/openhands/integrations/provider.py+++ b/openhands/integrations/provider.py@@ -187,13 +187,19 @@ class ProviderHandler:self, provider: ProviderType) -> SecretStr | None:"""Get latest token from service"""+ if not self.REFRESH_TOKEN_URL:+ logger.warning('Refresh token URL not set')+ return Nonetry:async with httpx.AsyncClient(verify=httpx_verify_option()) as client:+ headers = (+ {'X-Session-API-Key': self.session_api_key}+ if self.session_api_key+ else {}+ )resp = await client.get(self.REFRESH_TOKEN_URL,- headers={- 'X-Session-API-Key': self.session_api_key,- },+ headers=headers,params={'provider': provider.value, 'sid': self.sid},)diff --git a/openhands/llm/retry_mixin.py b/openhands/llm/retry_mixin.pyindex dee8ea470a..04148cd34d 100644--- a/openhands/llm/retry_mixin.py+++ b/openhands/llm/retry_mixin.py@@ -22,17 +22,17 @@ from openhands.utils.tenacity_stop import stop_if_should_exitclass RetryMixin:"""Mixin class for retry logic."""- def retry_decorator(self, **kwargs: Any) -> Callable:+ def retry_decorator(self, num_retries: int, **kwargs: Any) -> Callable:"""Create a LLM retry decorator with customizable parameters. This is used for 429 errors, and a few other exceptions in LLM classes.Args:+ num_retries: Number of retry attempts.**kwargs: Keyword arguments to override default retry behavior.- Keys: num_retries, retry_exceptions, retry_min_wait, retry_max_wait, retry_multiplier+ Keys: retry_exceptions, retry_min_wait, retry_max_wait, retry_multiplierReturns:A retry decorator with the parameters customizable in configuration."""- num_retries = kwargs.get('num_retries')retry_exceptions: tuple = kwargs.get('retry_exceptions', ())retry_min_wait = kwargs.get('retry_min_wait')retry_max_wait = kwargs.get('retry_max_wait')@@ -67,10 +67,11 @@ class RetryMixin:retry=(retry_if_exception_type(retry_exceptions)), # retry only for these types+ # TODO: Type errors here probably mean the defaults are being ignored.wait=wait_exponential(- multiplier=retry_multiplier,- min=retry_min_wait,- max=retry_max_wait,+ multiplier=retry_multiplier, # type: ignore[arg-type]+ min=retry_min_wait, # type: ignore[arg-type]+ max=retry_max_wait, # type: ignore[arg-type]),)return retry_decoratordiff --git a/openhands/mcp/client.py b/openhands/mcp/client.pyindex 5fc19a9062..b35f4be461 100644--- a/openhands/mcp/client.py+++ b/openhands/mcp/client.py@@ -49,7 +49,6 @@ class MCPClient(BaseModel):name=tool.name,description=tool.description,inputSchema=tool.inputSchema,- session=self.client,)self.tool_map[tool.name] = server_toolself.tools.append(server_tool)@@ -85,17 +84,17 @@ class MCPClient(BaseModel):# Instantiate custom transports due to custom headersif isinstance(server, MCPSHTTPServerConfig):- transport = StreamableHttpTransport(+ streamable_transport = StreamableHttpTransport(url=server_url,headers=headers if headers else None,)+ self.client = Client(streamable_transport, timeout=timeout)else:- transport = SSETransport(+ sse_transport = SSETransport(url=server_url,headers=headers if headers else None,)-- self.client = Client(transport, timeout=timeout)+ self.client = Client(sse_transport, timeout=timeout)await self._initialize_and_list_tools()except McpError as e:diff --git a/openhands/resolver/interfaces/bitbucket_data_center.py b/openhands/resolver/interfaces/bitbucket_data_center.pyindex c5bf4f9552..9931ef7493 100644--- a/openhands/resolver/interfaces/bitbucket_data_center.py+++ b/openhands/resolver/interfaces/bitbucket_data_center.py@@ -243,10 +243,12 @@ class BitbucketDCIssueHandler(IssueHandlerInterface):def branch_exists(self, branch_name: str) -> bool:url = f'{self._get_repo_api_base()}/branches'- params = {'filterText': branch_name, 'limit': 1}try:response = httpx.get(- url, headers=self.headers, params=params, verify=httpx_verify_option()+ url,+ headers=self.headers,+ params={'filterText': branch_name, 'limit': '1'},+ verify=httpx_verify_option(),)response.raise_for_status()data = response.json()diff --git a/openhands/runtime/builder/remote.py b/openhands/runtime/builder/remote.pyindex 820b89c3a6..6511baa193 100644--- a/openhands/runtime/builder/remote.py+++ b/openhands/runtime/builder/remote.py@@ -68,8 +68,8 @@ class RemoteRuntimeBuilder(RuntimeBuilder):files=files,timeout=30,)- except httpx.HTTPError as e:- if e.response.status_code == 429:+ except httpx.HTTPStatusError as e:+ if e.response and e.response.status_code == 429:logger.warning('Build was rate limited. Retrying in 30 seconds.')time.sleep(30)return self.build(path, tags, platform)diff --git a/openhands/runtime/impl/docker/docker_runtime.py b/openhands/runtime/impl/docker/docker_runtime.pyindex 968e338725..b85e29b7ab 100644--- a/openhands/runtime/impl/docker/docker_runtime.py+++ b/openhands/runtime/impl/docker/docker_runtime.py@@ -61,10 +61,10 @@ if os.name == 'nt' or platform.release().endswith('microsoft-standard-WSL2'):APP_PORT_RANGE_2 = (45000, 49151)-def _is_retryablewait_until_alive_error(exception: Exception) -> bool:+def _is_retryablewait_until_alive_error(exception: BaseException) -> bool:if isinstance(exception, tenacity.RetryError):cause = exception.last_attempt.exception()- return _is_retryablewait_until_alive_error(cause)+ return cause is not None and _is_retryablewait_until_alive_error(cause)return isinstance(exception,diff --git a/openhands/runtime/impl/local/local_runtime.py b/openhands/runtime/impl/local/local_runtime.pyindex ca55478c3e..0a11763433 100644--- a/openhands/runtime/impl/local/local_runtime.py+++ b/openhands/runtime/impl/local/local_runtime.py@@ -116,8 +116,12 @@ def check_dependencies(code_repo_path: str, check_browser: bool) -> None:except Exception:raise ValueError('tmux is not properly installed or available on the path.')pane = session.active_pane- pane.send_keys('echo "test"')- pane_output = '\n'.join(pane.cmd('capture-pane', '-p').stdout)++ if pane:+ pane.send_keys('echo "test"')+ pane_output = '\n'.join(pane.cmd('capture-pane', '-p').stdout)+ else:+ pane_output = ''session.kill()if 'test' not in pane_output:raise ValueError('libtmux is not properly installed. ' + ERROR_MESSAGE)diff --git a/openhands/runtime/impl/remote/remote_runtime.py b/openhands/runtime/impl/remote/remote_runtime.pyindex f851550637..1eefbd8282 100644--- a/openhands/runtime/impl/remote/remote_runtime.py+++ b/openhands/runtime/impl/remote/remote_runtime.py@@ -40,7 +40,15 @@ from openhands.runtime.utils.command import (from openhands.runtime.utils.request import send_requestfrom openhands.runtime.utils.runtime_build import build_runtime_imagefrom openhands.utils.async_utils import call_sync_from_async-from openhands.utils.tenacity_stop import stop_if_should_exit+from openhands.utils.tenacity_stop import stop_base, stop_if_should_exit+++class _StopIfClosed(stop_base):+ def __init__(self, runtime: ActionExecutionClient):+ self.runtime = runtime++ def __call__(self, retry_state):+ return self.runtime._runtime_closedclass RemoteRuntime(ActionExecutionClient):@@ -189,18 +197,26 @@ class RemoteRuntime(ActionExecutionClient):self.log('info', f'Found runtime with status: {status}')if status == 'running' or status == 'paused':self._parse_runtime_response(response)- except httpx.HTTPError as e:+ except httpx.HTTPStatusError as e:if e.response.status_code == 404:self.log('info', f'No existing runtime found for session ID: {self.sid}')return False- self.log('error', f'Error while looking for remote runtime: {e}')+ self.log(+ 'error', f'Error while looking for remote runtime: {e}', exc_info=True+ )+ raise+ except httpx.HTTPError as e:+ self.log(+ 'error', f'Error while looking for remote runtime: {e}', exc_info=True+ )raiseexcept json.decoder.JSONDecodeError as e:self.log('error',f'Invalid JSON response from runtime API: {e}. URL: {self.config.sandbox.remote_runtime_api_url}/sessions/{self.sid}. Response: {response}',+ exc_info=True,)raise@@ -413,7 +429,7 @@ class RemoteRuntime(ActionExecutionClient):self.config.sandbox.remote_runtime_init_timeout)| stop_if_should_exit()- | self._stop_if_closed,+ | _StopIfClosed(self),reraise=True,retry=tenacity.retry_if_exception_type(AgentRuntimeNotReadyError),wait=tenacity.wait_fixed(2),@@ -545,8 +561,11 @@ class RemoteRuntime(ActionExecutionClient):retry=tenacity.retry_if_exception_type(httpx.NetworkError),stop=tenacity.stop_after_attempt(3)| stop_if_should_exit()- | self._stop_if_closed,- before_sleep=tenacity.before_sleep_log(logger, logging.WARNING),+ | _StopIfClosed(self),+ before_sleep=tenacity.before_sleep_log(+ logger, # type: ignore[arg-type]+ logging.WARNING,+ ),wait=tenacity.wait_exponential(multiplier=1, min=4, max=60),)return retry_decorator(self._send_action_server_request_impl)(diff --git a/openhands/runtime/plugins/jupyter/__init__.py b/openhands/runtime/plugins/jupyter/__init__.pyindex b5660864bf..3ecad877d1 100644--- a/openhands/runtime/plugins/jupyter/__init__.py+++ b/openhands/runtime/plugins/jupyter/__init__.py@@ -171,16 +171,18 @@ class JupyterPlugin(Plugin):await self.kernel.initialize()# Execute the code and get structured output- output = await self.kernel.execute(action.code, timeout=action.timeout)-+ if action.timeout:+ output = await self.kernel.execute(action.code, timeout=int(action.timeout))+ else:+ output = await self.kernel.execute(action.code)# Extract text content and image URLs from the structured outputtext_content = output.get('text', '')image_urls = output.get('images', [])return IPythonRunCellObservation(- content=text_content,+ content=text_content, # type: ignore[arg-type]code=action.code,- image_urls=image_urls if image_urls else None,+ image_urls=image_urls if image_urls else None, # type: ignore[arg-type])async def run(self, action: Action) -> IPythonRunCellObservation:diff --git a/openhands/runtime/utils/bash.py b/openhands/runtime/utils/bash.pyindex 66bc399a0a..b021042aa2 100644--- a/openhands/runtime/utils/bash.py+++ b/openhands/runtime/utils/bash.py@@ -239,7 +239,7 @@ class BashSession:# Set history limit to a large number to avoid losing history# https://unix.stackexchange.com/questions/43414/unlimited-history-in-tmuxself.session.set_option('history-limit', str(self.HISTORY_LIMIT), global_=True)- self.session.history_limit = self.HISTORY_LIMIT+ self.session.history_limit = str(self.HISTORY_LIMIT)# We need to create a new pane because the initial pane's history limit is (default) 2000_initial_window = self.session.active_windowself.window = self.session.new_window(@@ -252,9 +252,10 @@ class BashSession:_initial_window.kill()# Configure bash to use simple PS1 and disable PS2- self.pane.send_keys(- f'export PROMPT_COMMAND=\'export PS1="{self.PS1}"\'; export PS2=""'- )+ if self.pane:+ self.pane.send_keys(+ f'export PROMPT_COMMAND=\'export PS1="{self.PS1}"\'; export PS2=""'+ )time.sleep(0.1) # Wait for command to take effectself._clear_screen()@@ -274,6 +275,8 @@ class BashSession:def _get_pane_content(self) -> str:"""Capture the current pane content and update the buffer."""+ if not self.pane:+ return ''content = '\n'.join(map(# avoid double newlines@@ -302,9 +305,10 @@ class BashSession:def _clear_screen(self) -> None:"""Clear the tmux pane screen and history."""- self.pane.send_keys('C-l', enter=False)- time.sleep(0.1)- self.pane.cmd('clear-history')+ if self.pane:+ self.pane.send_keys('C-l', enter=False)+ time.sleep(0.1)+ self.pane.cmd('clear-history')def _get_command_output(self,@@ -596,7 +600,7 @@ class BashSession:)# Send actual command/inputs to the pane- if command != '':+ if command != '' and self.pane:is_special_key = self._is_special_key(command)if is_input:logger.debug(f'SENDING INPUT TO RUNNING PROCESS: {command!r}')diff --git a/openhands/runtime/utils/request.py b/openhands/runtime/utils/request.pyindex 3c71b28325..8a5161f8fb 100644--- a/openhands/runtime/utils/request.py+++ b/openhands/runtime/utils/request.py@@ -9,6 +9,7 @@ import jsonfrom typing import Anyimport httpx+from httpx import HTTPStatusErrorfrom tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponentialfrom openhands.utils.http_session import HttpSession@@ -58,10 +59,11 @@ def send_request(_json = Nonefinally:response.close()+raise RequestHTTPError(e,request=e.request,- response=e.response,+ response=e.response if isinstance(e, HTTPStatusError) else None,detail=_json.get('detail') if _json is not None else None,) from ereturn responsediff --git a/openhands/security/grayswan/analyzer.py b/openhands/security/grayswan/analyzer.pyindex 926e4710bf..7a8c50508b 100644--- a/openhands/security/grayswan/analyzer.py+++ b/openhands/security/grayswan/analyzer.py@@ -96,7 +96,7 @@ class GraySwanAnalyzer(SecurityAnalyzer):if self.session is None:self.session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout),- headers={+ headers={ # type: ignore[arg-type]'Authorization': f'Bearer {self.api_key}','x-grayswan-api-key': self.api_key,'Content-Type': 'application/json',@@ -105,7 +105,7 @@ class GraySwanAnalyzer(SecurityAnalyzer):elif hasattr(self.session, 'closed') and self.session.closed:self.session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout),- headers={+ headers={ # type: ignore[arg-type]'Authorization': f'Bearer {self.api_key}','x-grayswan-api-key': self.api_key,'Content-Type': 'application/json',diff --git a/openhands/server/routes/manage_conversations.py b/openhands/server/routes/manage_conversations.pyindex 1d2661d369..cab0755111 100644--- a/openhands/server/routes/manage_conversations.py+++ b/openhands/server/routes/manage_conversations.py@@ -674,9 +674,14 @@ async def _get_num_conversations_in_sandbox(agent_server_url = next(u for u in sandbox.exposed_urls if u.name == AGENT_SERVER)+ headers = (+ {'X-Session-API-Key': sandbox.session_api_key}+ if sandbox.session_api_key+ else {}+ )response = await httpx_client.get(f'{agent_server_url.url}/api/conversations/count',- headers={'X-Session-API-Key': sandbox.session_api_key},+ headers=headers,)result = int(response.content)return result@@ -1570,9 +1575,12 @@ def _to_conversation_info(app_conversation: AppConversation) -> ConversationInfoConversationExecutionStatus.FINISHED: RuntimeStatus.READY,ConversationExecutionStatus.STUCK: RuntimeStatus.ERROR,}- runtime_status = runtime_status_mapping.get(- app_conversation.execution_status, RuntimeStatus.ERROR- )+ if app_conversation.execution_status:+ runtime_status = runtime_status_mapping.get(+ app_conversation.execution_status, RuntimeStatus.ERROR+ )+ else:+ runtime_status = RuntimeStatus.ERRORelse:runtime_status = Nonediff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.pyindex 0a765b1dda..849aedcf88 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@@ -907,7 +907,6 @@ class TestLiveStatusAppConversationService:== 'test_plan_structure')assert call_kwargs['mcp_config'] == mcp_config- assert call_kwargs['security_analyzer'] is Noneassert call_kwargs['condenser'] == mock_condensermock_create_condenser.assert_called_once_with(mock_llm, AgentType.PLAN, self.mock_user.condenser_max_size