Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Revert ACP bootstrap-prompt resume + enable acp_isolate_data_dir on the cloud start path (#14722)

simonrosenbergb34a7491c040
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 5b4ae92465..6badb8d3ea 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
@@ -2,7 +2,6 @@ import asyncio
import json
import logging
import os
-import re
import tempfile
import zipfile
from collections import defaultdict
@@ -18,7 +17,6 @@ from pydantic import Field, SecretStr, TypeAdapter
from openhands.agent_server.models import (
ConversationInfo,
- EventSortOrder,
SendMessageRequest,
StartConversationRequest,
TextContent,
@@ -97,8 +95,6 @@ from openhands.app_server.utils.llm_metadata import (
should_set_litellm_extra_body,
)
from openhands.sdk import Agent, AgentContext, LocalWorkspace
-from openhands.sdk.event import RESUME_CONTEXT_MARKER, render_resume_transcript
-from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
from openhands.sdk.hooks import HookConfig
from openhands.sdk.llm import LLM
from openhands.sdk.llm.llm_profile_store import PROFILE_NAME_REGEX
@@ -126,186 +122,6 @@ from openhands.tools.preset.planning import (
_conversation_info_type_adapter = TypeAdapter(list[ConversationInfo | None])
_logger = logging.getLogger(__name__)
-# Limits for bootstrap-prompt resume (Solution A of issue #14260).
-# Generic rendering is handled by openhands.sdk.event.render_resume_transcript.
-# The fetch/pagination wrapper, double-resume guard, and provider-specific
-# scrubbing (_sanitize_paths, _strip_terminal_boilerplate, _extract_output_text,
-# _format_raw_input, _RAW_INPUT_NOISE_KEYS) stay here β€” they encode sandbox-
-# lifecycle and Codex-shape concerns the SDK layer deliberately doesn't know about.
-_ACP_RESUME_MAX_EVENTS = 200 # hard event-count cap (prevents O(N) fetches)
-_ACP_RESUME_CONTEXT_MAX_CHARS = 60_000 # total resume block
-_ACP_RESUME_MESSAGE_MAX_CHARS = 8_000 # per message turn
-_ACP_RESUME_TOOL_MAX_CHARS = 2_000 # per tool event
-
-
-def _truncate_keep_head(text: str, max_chars: int) -> str:
- """Truncate to at most max_chars, keeping the start."""
- if max_chars <= 0:
- return ''
- if len(text) <= max_chars:
- return text
- if max_chars < 4:
- return text[:max_chars]
- return text[: max_chars - 3] + '...'
-
-
-_ABS_PATH_RE = re.compile(r'/[^\s\'",:}\]]{10,}')
-
-
-# Pytest/terminal boilerplate lines to strip from command output.
-_TERMINAL_BOILERPLATE_RE = re.compile(
- r'^(?:'
- r'={10,}.*test session starts.*={10,}'
- r'|platform \w+'
- r'|cachedir:'
- r'|rootdir:'
- r'|plugins:'
- r'|asyncio:'
- r'|collecting \.\.\.'
- r')',
- re.MULTILINE,
-)
-
-
-def _strip_terminal_boilerplate(text: str) -> str:
- """Remove pytest/shell boilerplate header lines from command output.
-
- Strips ``platform``, ``cachedir``, ``rootdir``, ``plugins``, ``asyncio``,
- and ``collecting ...`` lines that carry no useful information for a resumed
- agent. The test result lines (PASSED/FAILED/ERROR) and summary are kept.
- """
- lines = [ln for ln in text.splitlines() if not _TERMINAL_BOILERPLATE_RE.match(ln)]
- # Collapse runs of blank lines left behind after stripping.
- out: list[str] = []
- prev_blank = False
- for ln in lines:
- blank = not ln.strip()
- if blank and prev_blank:
- continue
- out.append(ln)
- prev_blank = blank
- return '\n'.join(out).strip()
-
-
-# Provider-internal metadata keys that add no value to a resume message.
-# Codex execute tools include call_id, process_id, turn_id, timestamps, etc.
-# 'cwd' is always the sandbox working directory β€” after path sanitization it
-# shows as the sandbox ID, which is meaningless; drop it too.
-_RAW_INPUT_NOISE_KEYS = frozenset(
- {
- 'call_id',
- 'process_id',
- 'turn_id',
- 'started_at_ms',
- 'completed_at_ms',
- 'parsed_cmd',
- 'source',
- 'auto_approved',
- 'cwd',
- }
-)
-
-
-def _extract_output_text(raw_output: object) -> str:
- """Extract the human-readable text from a tool's raw_output.
-
- Some ACP providers (e.g. Codex) wrap stdout/stderr in a dict alongside
- metadata. We pull out just the meaningful content so the agent sees the
- actual command output rather than a Python dict repr.
- """
- if isinstance(raw_output, dict):
- stdout = str(raw_output.get('stdout', '') or '').strip()
- stderr = str(raw_output.get('stderr', '') or '').strip()
- parts = []
- if stdout:
- parts.append(stdout)
- if stderr:
- parts.append(f'[stderr]: {stderr}')
- if parts:
- return '\n'.join(parts)
- # dict but no stdout/stderr keys β€” fall through to repr
- return str(raw_output)
-
-
-def _format_raw_input(raw: dict, max_chars: int, is_edit_diff: bool = False) -> str:
- """Render a tool's raw_input dict in a readable form.
-
- For edit-diff tools only the filename is shown β€” the file on the
- persistent /workspace PVC is the source of truth.
-
- For Codex-style changes dicts (``{path: {type, content}}``) the file
- contents are rendered under their sanitized basenames.
-
- For execute tools internal metadata keys (call_id, process_id, …) are
- stripped; a list-valued ``command`` field is unwrapped to its last element.
-
- For all other tools, multiline string values are rendered with real
- newlines; single-line values as ``key=value``.
- """
- if is_edit_diff:
- # Patch/diff: file is on /workspace β€” just show the filename.
- fp = _sanitize_paths(str(raw.get('file_path', '')))
- return f'file={fp}'
-
- # Codex-style bulk changes: {abs_path: {type, content}, …}
- if 'changes' in raw and isinstance(raw.get('changes'), dict):
- changes = raw['changes']
- parts: list[str] = []
- for path, change in changes.items():
- basename = os.path.basename(str(path)) if path else 'file'
- content = str(change.get('content', '') or '')
- change_type = change.get('type', 'edit')
- if content:
- parts.append(
- f'{change_type} {basename}:\n{_truncate_keep_head(content, 400)}'
- )
- else:
- parts.append(f'{change_type} {basename}')
- return _truncate_keep_head('\n'.join(parts), max_chars)
-
- # General case: filter noise keys, extract command list, sanitize values.
- cleaned: dict[str, object] = {}
- for k, v in raw.items():
- if k in _RAW_INPUT_NOISE_KEYS:
- continue
- # Unwrap list-valued command: ['/bin/zsh', '-lc', 'actual cmd'] β†’ 'actual cmd'
- if k == 'command' and isinstance(v, list) and v:
- cleaned[k] = v[-1]
- else:
- cleaned[k] = v
-
- out_parts: list[str] = []
- for k, v in cleaned.items():
- if isinstance(v, str):
- v_san = _sanitize_paths(v)
- if '\n' in v_san:
- out_parts.append(f'{k}:\n{v_san}')
- else:
- out_parts.append(f'{k}={v_san}')
- else:
- out_parts.append(f'{k}={_sanitize_paths(str(v))}')
- return _truncate_keep_head('\n'.join(out_parts), max_chars)
-
-
-def _sanitize_paths(text: str) -> str:
- """Replace absolute filesystem paths with their basename.
-
- ACP tool raw_input/raw_output often contains the full ephemeral sandbox
- path (e.g. /private/var/folders/.../hello.py). That path is meaningless
- in a resumed session and could confuse the agent about file locations.
- We keep only the basename so the agent retains the filename intent.
- """
-
- def _replace(m: re.Match) -> str: # type: ignore[type-arg]
- path = m.group(0)
- # Only shorten paths that look like absolute filesystem paths, not URLs.
- if path.startswith('//') or '://' in path:
- return path
- base = os.path.basename(path.rstrip('/'))
- return base if base else path
-
- return _ABS_PATH_RE.sub(_replace, text)
-
# Planning agent instruction to prevent "Ready to proceed?" behavior
PLANNING_AGENT_INSTRUCTION = """<IMPORTANT_PLANNING_BOUNDARIES>
@@ -1773,136 +1589,6 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
_logger.warning(f'Failed to load skills: {e}', exc_info=True)
return request
- async def _synthesize_acp_resume_initial_message(
- self,
- conversation_id: UUID,
- initial_message: SendMessageRequest | None = None,
- ) -> SendMessageRequest | None:
- """Build a bootstrap-prompt resume message from the durable event store.
-
- When a sandbox is recycled the ACP server's own session storage is gone,
- so ``session/load`` cannot be used. Instead we start a fresh
- ``new_session`` and inject the prior event history as the first user
- message (Solution A of issue #14260).
-
- Returns ``None`` when there are no prior events (fresh conversation).
- If ``initial_message`` is provided it is appended after the history block
- so the agent receives both context and the new user turn.
- """
- # Guard: don't double-wrap an already-synthesized resume message.
- if initial_message and initial_message.content:
- first_text = getattr(initial_message.content[0], 'text', None)
- if isinstance(first_text, str) and first_text.startswith(
- RESUME_CONTEXT_MARKER
- ):
- return initial_message
-
- # Fetch newest-first so that when the conversation exceeds
- # _ACP_RESUME_MAX_EVENTS we keep the most recent context, not the oldest.
- # The count cap avoids O(N) fetches for very long conversations; the
- # character cap (_ACP_RESUME_CONTEXT_MAX_CHARS) is applied at render time.
- all_events: list = []
- try:
- page_id: str | None = None
- while len(all_events) < _ACP_RESUME_MAX_EVENTS:
- page = await self.event_service.search_events(
- conversation_id,
- sort_order=EventSortOrder.TIMESTAMP_DESC,
- page_id=page_id,
- limit=100,
- )
- all_events.extend(page.items)
- if len(all_events) >= _ACP_RESUME_MAX_EVENTS:
- all_events = all_events[:_ACP_RESUME_MAX_EVENTS]
- break
- if page.next_page_id is None:
- break
- page_id = page.next_page_id
- except Exception:
- _logger.warning(
- 'Failed to fetch events for ACP resume of conversation %s',
- conversation_id,
- exc_info=True,
- )
- return initial_message
- all_events.reverse()
-
- # Pre-process ACPToolCallEvents with OpenHands-specific scrubbing before
- # handing to the SDK renderer:
- # - _format_raw_input: filters Codex noise keys, handles Codex bulk-changes
- # shape, strips diff content (file is durable on /workspace).
- # - _extract_output_text: unwraps Codex {stdout, stderr} output dicts.
- # - _strip_terminal_boilerplate: removes pytest/shell header lines.
- # _sanitize_paths is applied post-render so it also catches tool titles
- # and message text that the SDK renders without knowing about sandbox paths.
- # Placeholder events (ACP streams before params arrive) are dropped here.
- scrubbed: list = []
- for event in all_events:
- if not isinstance(event, ACPToolCallEvent):
- scrubbed.append(event)
- continue
- if (
- not event.raw_input
- and event.raw_output is None
- and not event.is_error
- and not event.content
- ):
- continue
- raw_in = dict(event.raw_input) if isinstance(event.raw_input, dict) else {}
- scrubbed_input: object = (
- _format_raw_input(raw_in, 800, is_edit_diff=event.is_patch_edit)
- if raw_in
- else None
- )
- scrubbed_output: object = event.raw_output
- if event.raw_output is not None:
- raw_out = _strip_terminal_boilerplate(
- _sanitize_paths(_extract_output_text(event.raw_output))
- )
- if event.is_error and len(raw_out) > 800:
- raw_out = '...\n' + raw_out[-800:]
- else:
- raw_out = _truncate_keep_head(raw_out, 800)
- scrubbed_output = raw_out
- scrubbed.append(
- event.model_copy(
- update={'raw_input': scrubbed_input, 'raw_output': scrubbed_output}
- )
- )
-
- resume_text = render_resume_transcript(
- scrubbed,
- header_body=(
- 'The sandbox was recycled and the ACP agent session storage was lost. '
- 'The following is the conversation history from the previous session. '
- 'Please treat this as context and continue from where we left off.'
- ),
- max_chars=_ACP_RESUME_CONTEXT_MAX_CHARS,
- max_message_chars=_ACP_RESUME_MESSAGE_MAX_CHARS,
- max_tool_chars=_ACP_RESUME_TOOL_MAX_CHARS,
- )
- if resume_text is None:
- return initial_message
-
- # Sanitize paths in the rendered text (tool titles, message bodies, etc.)
- resume_text = _sanitize_paths(resume_text)
-
- if initial_message is None:
- return SendMessageRequest(
- role='user',
- content=[TextContent(type='text', text=resume_text)],
- )
-
- # Preserve the new user turn as a separate content block after the history.
- return SendMessageRequest(
- role=initial_message.role,
- content=[
- TextContent(type='text', text=resume_text),
- *initial_message.content,
- ],
- run=getattr(initial_message, 'run', None),
- )
-
async def _build_acp_start_conversation_request(
self,
sandbox: SandboxInfo,
@@ -1953,16 +1639,6 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
)
secrets[name] = StaticSecret(value=value)
- # --- bootstrap-prompt resume (Solution A of issue #14260) -----------
- # If this conversation has prior events in the durable store the sandbox
- # was recycled and the ACP server's session storage is gone. Synthesize
- # the history as the opening content block so the agent has context.
- resume_result = await self._synthesize_acp_resume_initial_message(
- conversation_id, initial_message
- )
- if resume_result is not None:
- initial_message = resume_result
-
# --- build the ACP agent ------------------------------------------
acp_settings = user.agent_settings # already verified to be ACPAgentSettings
assert isinstance(acp_settings, ACPAgentSettings)
@@ -1971,9 +1647,12 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
# (sdk#3464). Pass SecretSource objects verbatim β€” the SDK resolves them
# at subprocess launch, not here, to avoid eager LookupSecret calls.
agent_context = AgentContext(secrets=secrets) if secrets else None
- settings_update = (
- {'agent_context': agent_context} if agent_context is not None else {}
- )
+ # Isolate the CLI data dir onto the durable /workspace tree so the SDK
+ # self-resumes the provider session (session/load from base_state.json)
+ # across pause/resume β€” matching the regular-agent lifecycle (#1274).
+ settings_update: dict[str, object] = {'acp_isolate_data_dir': True}
+ if agent_context is not None:
+ settings_update['agent_context'] = agent_context
acp_agent = acp_settings.model_copy(update=settings_update).create_agent()
sdk_plugins: list[PluginSource] | None = None
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 a004b216f2..825f891742 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
@@ -3317,14 +3317,8 @@ class TestBuildAcpStartConversationRequestSecrets:
def _call_build(self, service, user, tmp_path):
"""Wire user_context and call _build_acp_start_conversation_request."""
- from openhands.agent_server.models import EventPage
-
service.user_context.get_user_info = AsyncMock(return_value=user)
service.user_context.get_user_email = AsyncMock(return_value=None)
- # Fresh conversation β€” no prior events, so resume synthesis returns None.
- service.event_service.search_events = AsyncMock(
- return_value=EventPage(items=[], next_page_id=None)
- )
sandbox = Mock(spec=SandboxInfo)
return service._build_acp_start_conversation_request(
sandbox=sandbox,
@@ -3350,6 +3344,8 @@ class TestBuildAcpStartConversationRequestSecrets:
ctx = request.agent.agent_context.secrets
assert ctx.get('GITHUB_TOKEN') is github_secret
assert ctx.get('MY_API_KEY') is api_secret
+ # Isolation is enabled regardless of whether secrets are present.
+ assert request.agent.acp_isolate_data_dir is True
@pytest.mark.asyncio
async def test_lookup_secret_forwarded_as_source(self, service, tmp_path):
@@ -3402,6 +3398,18 @@ class TestBuildAcpStartConversationRequestSecrets:
assert request.agent.agent_context is None
+ @pytest.mark.asyncio
+ async def test_isolate_data_dir_enabled(self, service, tmp_path):
+ """The cloud start path builds the ACP agent with data-dir isolation on
+ so the CLI session subtree lives on /workspace and the SDK self-resumes
+ across pause/resume (#1274)."""
+ user = self._make_acp_user()
+ service._setup_secrets_for_git_providers = AsyncMock(return_value={})
+
+ request = await self._call_build(service, user, tmp_path)
+
+ assert request.agent.acp_isolate_data_dir is True
+
@pytest.mark.asyncio
async def test_acp_env_overrides_provider_env(self, service, tmp_path):
"""Explicit acp_env entry beats the provider cred (acp_env > agent_context.secrets at launch)."""
@@ -3472,698 +3480,3 @@ class TestBuildAcpStartConversationRequestSecrets:
request = await self._call_build(service, user, tmp_path)
assert request.agent.acp_env.get('GH_TOKEN') == 'explicit-token'
-
-
-class TestSynthesizeAcpResumeInitialMessage:
- """Tests for _synthesize_acp_resume_initial_message (Solution A, issue #14260).
-
- Verifies that bootstrap-prompt resume correctly converts the durable event
- store into an initial_message for a fresh ACP new_session when the sandbox
- is recycled and the agent's own session storage is gone.
- """
-
- @pytest.fixture
- def service(self):
- return LiveStatusAppConversationService(
- init_git_in_empty_workspace=True,
- user_context=Mock(spec=UserContext),
- app_conversation_info_service=Mock(),
- app_conversation_start_task_service=Mock(),
- event_callback_service=Mock(),
- event_service=Mock(),
- sandbox_service=Mock(),
- sandbox_spec_service=Mock(),
- jwt_service=Mock(),
- pending_message_service=Mock(),
- sandbox_startup_timeout=30,
- sandbox_startup_poll_frequency=1,
- max_num_conversations_per_sandbox=20,
- httpx_client=Mock(),
- web_url=None,
- openhands_provider_base_url=None,
- access_token_hard_timeout=None,
- app_mode='test',
- )
-
- def _make_empty_page(self):
- from openhands.agent_server.models import EventPage
-
- return EventPage(items=[], next_page_id=None)
-
- def _make_page(self, items, next_page_id=None):
- from openhands.agent_server.models import EventPage
-
- return EventPage(items=items, next_page_id=next_page_id)
-
- def _make_message_event(self, role, text):
- from openhands.sdk import MessageEvent
- from openhands.sdk.llm.message import Message
- from openhands.sdk.llm.message import TextContent as MsgTextContent
-
- msg = Message(role=role, content=[MsgTextContent(type='text', text=text)])
- return MessageEvent(
- source='user' if role == 'user' else 'agent', llm_message=msg
- )
-
- def _make_tool_event(
- self,
- title,
- is_error=False,
- status=None,
- tool_call_id=None,
- raw_input=None,
- raw_output=None,
- ):
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- return ACPToolCallEvent(
- source='agent',
- tool_call_id=tool_call_id or f'tc-{title}',
- title=title,
- is_error=is_error,
- status=status,
- raw_input=raw_input or {},
- raw_output=raw_output,
- )
-
- @pytest.mark.asyncio
- async def test_no_events_returns_none(self, service):
- """Fresh conversations have no prior events; nothing to synthesize."""
- service.event_service.search_events = AsyncMock(
- return_value=self._make_empty_page()
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is None
-
- @pytest.mark.asyncio
- async def test_only_irrelevant_events_returns_none(self, service):
- """Events that are neither MessageEvent nor ACPToolCallEvent β†’ no resume."""
- from openhands.sdk.event.conversation_state import ConversationStateUpdateEvent
-
- state_event = ConversationStateUpdateEvent(
- source='agent', key='status', value='running'
- )
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([state_event])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is None
-
- @pytest.mark.asyncio
- async def test_message_events_produce_role_tagged_turns(self, service):
- """MessageEvents are rendered as [USER] / [ASSISTANT] tagged lines."""
- events = [
- self._make_message_event('user', 'Please refactor the login module.'),
- self._make_message_event('assistant', 'Sure, I will start now.'),
- ]
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page(events)
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- assert result.role == 'user'
- text = result.content[0].text
- assert '<<RESUMED CONVERSATION>>' in text
- assert '[USER]: Please refactor the login module.' in text
- assert '[ASSISTANT]: Sure, I will start now.' in text
-
- @pytest.mark.asyncio
- async def test_tool_events_produce_tool_use_lines(self, service):
- """ACPToolCallEvents appear as [TOOL USE: …] summary lines."""
- events = [
- self._make_tool_event(
- 'Write File',
- is_error=False,
- status='completed',
- tool_call_id='tc-write',
- raw_input={'content': 'x'},
- ),
- self._make_tool_event(
- 'Run Tests',
- is_error=True,
- tool_call_id='tc-run',
- raw_input={'cmd': 'pytest'},
- ),
- ]
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page(events)
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- assert '[TOOL USE: Write File] (completed)' in text
- assert '[TOOL USE: Run Tests] (failed)' in text
-
- @pytest.mark.asyncio
- async def test_mixed_events_preserve_order(self, service):
- """Message and tool events appear in chronological order after DESC fetch + reverse."""
- # search_events is called with TIMESTAMP_DESC (newest first); mock matches that order.
- events = [
- self._make_message_event('assistant', 'Done reading'),
- self._make_tool_event('Read File', raw_input={'path': 'auth.py'}),
- self._make_message_event('user', 'First message'),
- ]
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page(events)
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- first_pos = text.index('[USER]: First message')
- tool_pos = text.index('[TOOL USE: Read File]')
- agent_pos = text.index('[ASSISTANT]: Done reading')
- assert first_pos < tool_pos < agent_pos
-
- @pytest.mark.asyncio
- async def test_pagination_collects_all_events(self, service):
- """All pages are fetched until next_page_id is None."""
- from openhands.agent_server.models import EventPage
-
- page1 = EventPage(
- items=[self._make_message_event('user', 'Page 1 message')],
- next_page_id='page2',
- )
- page2 = EventPage(
- items=[self._make_message_event('assistant', 'Page 2 reply')],
- next_page_id=None,
- )
- service.event_service.search_events = AsyncMock(side_effect=[page1, page2])
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- assert '[USER]: Page 1 message' in text
- assert '[ASSISTANT]: Page 2 reply' in text
- assert service.event_service.search_events.call_count == 2
-
- @pytest.mark.asyncio
- async def test_no_prior_events_initial_message_unchanged(self, service):
- """Fresh start: no events β†’ initial_message flows through unchanged."""
- try:
- from openhands.sdk.settings import ACPAgentSettings
- except ImportError:
- pytest.skip('ACPAgentSettings not available in this SDK build')
-
- service.event_service.search_events = AsyncMock(
- return_value=self._make_empty_page()
- )
-
- user = _TestUserInfo(
- id='u1',
- llm_model='',
- llm_base_url=None,
- llm_api_key=None,
- sandbox_grouping_strategy=SandboxGroupingStrategy.ADD_TO_ANY,
- confirmation_mode=False,
- security_analyzer=None,
- search_api_key=None,
- mcp_config=None,
- disabled_skills=[],
- )
- user.agent_settings = ACPAgentSettings(
- acp_server='codex',
- llm=LLM(model='claude-sonnet-4-5'),
- acp_env={},
- )
- service.user_context.get_user_info = AsyncMock(return_value=user)
- service.user_context.get_user_email = AsyncMock(return_value=None)
- service._setup_secrets_for_git_providers = AsyncMock(return_value={})
-
- import tempfile
-
- with tempfile.TemporaryDirectory() as tmp:
- user_msg = SendMessageRequest(
- role='user', content=[TextContent(type='text', text='Brand new task')]
- )
- req = await service._build_acp_start_conversation_request(
- sandbox=Mock(spec=SandboxInfo),
- conversation_id=uuid4(),
- initial_message=user_msg,
- working_dir=tmp,
- )
-
- assert req.initial_message is not None
- all_text = ' '.join(c.text for c in req.initial_message.content)
- assert '<<RESUMED CONVERSATION>>' not in all_text
- assert 'Brand new task' in all_text
-
- @pytest.mark.asyncio
- async def test_restart_no_user_message_uses_resume_as_initial(self, service):
- """Restart with no new user message β†’ synthesized history is initial_message."""
- try:
- from openhands.sdk.settings import ACPAgentSettings
- except ImportError:
- pytest.skip('ACPAgentSettings not available in this SDK build')
-
- events = [
- self._make_message_event('user', 'Original task'),
- self._make_tool_event('Execute Code', raw_input={'cmd': 'python test.py'}),
- self._make_message_event('assistant', 'All done'),
- ]
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page(events)
- )
-
- user = _TestUserInfo(
- id='u1',
- llm_model='',
- llm_base_url=None,
- llm_api_key=None,
- sandbox_grouping_strategy=SandboxGroupingStrategy.ADD_TO_ANY,
- confirmation_mode=False,
- security_analyzer=None,
- search_api_key=None,
- mcp_config=None,
- disabled_skills=[],
- )
- user.agent_settings = ACPAgentSettings(
- acp_server='gemini-cli',
- llm=LLM(model='claude-sonnet-4-5'),
- acp_env={},
- )
- service.user_context.get_user_info = AsyncMock(return_value=user)
- service.user_context.get_user_email = AsyncMock(return_value=None)
- service._setup_secrets_for_git_providers = AsyncMock(return_value={})
-
- import tempfile
-
- with tempfile.TemporaryDirectory() as tmp:
- req = await service._build_acp_start_conversation_request(
- sandbox=Mock(spec=SandboxInfo),
- conversation_id=uuid4(),
- initial_message=None,
- working_dir=tmp,
- )
-
- assert req.initial_message is not None
- text = req.initial_message.content[0].text
- assert '<<RESUMED CONVERSATION>>' in text
- assert '[USER]: Original task' in text
- assert '[TOOL USE: Execute Code]' in text
- assert '[ASSISTANT]: All done' in text
- assert '--- End of prior session ---' in text
-
- @pytest.mark.asyncio
- async def test_double_resume_guard(self, service):
- """A message already starting with the marker is not re-wrapped."""
- already_resumed = SendMessageRequest(
- role='user',
- content=[
- TextContent(type='text', text='<<RESUMED CONVERSATION>>\nprior history')
- ],
- )
- # search_events should never be called
- service.event_service.search_events = AsyncMock()
-
- result = await service._synthesize_acp_resume_initial_message(
- uuid4(), already_resumed
- )
-
- assert result is already_resumed
- service.event_service.search_events.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_event_fetch_error_returns_initial_message(self, service):
- """If search_events raises, fall back to initial_message unchanged."""
- service.event_service.search_events = AsyncMock(
- side_effect=RuntimeError('storage unavailable')
- )
- original = SendMessageRequest(
- role='user', content=[TextContent(type='text', text='My task')]
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4(), original)
-
- assert result is original
-
- @pytest.mark.asyncio
- async def test_new_user_message_preserved_as_second_content_block(self, service):
- """When a new user message accompanies prior events, both appear in content."""
- events = [self._make_message_event('user', 'Prior task')]
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page(events)
- )
- new_msg = SendMessageRequest(
- role='user',
- content=[TextContent(type='text', text='Now do the next step.')],
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4(), new_msg)
-
- assert result is not None
- assert len(result.content) == 2
- assert '<<RESUMED CONVERSATION>>' in result.content[0].text
- assert result.content[1].text == 'Now do the next step.'
-
- @pytest.mark.asyncio
- async def test_tool_events_include_raw_input_output(self, service):
- """raw_input and raw_output are included in the tool summary."""
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- tool = ACPToolCallEvent(
- source='agent',
- tool_call_id='tc-99',
- title='Edit File',
- status='completed',
- raw_input={'path': 'auth.py', 'content': 'def login(): pass'},
- raw_output='ok',
- )
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([tool])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- # New rendering: input/output on separate labelled lines, not as dict repr
- assert 'input:' in text
- assert 'path=auth.py' in text
- assert 'output:' in text
- assert 'ok' in text
-
- @pytest.mark.asyncio
- async def test_long_conversation_truncated_to_max_chars(self, service):
- """Output is capped at _ACP_RESUME_CONTEXT_MAX_CHARS.
-
- Tail-preserving: newest events survive and the footer is kept intact.
- The oldest events are dropped (head of the body is truncated with '...').
- """
- from openhands.app_server.app_conversation.live_status_app_conversation_service import (
- _ACP_RESUME_CONTEXT_MAX_CHARS,
- )
-
- long_text = 'x' * 10_000
- # 10 events Γ— 10k chars each far exceeds the 60k limit
- events = [self._make_message_event('user', long_text) for _ in range(10)]
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page(events)
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- assert len(text) <= _ACP_RESUME_CONTEXT_MAX_CHARS
- # Tail-preserving: footer survives instead of being cut off.
- assert text.endswith('--- End of prior session ---')
- # Body was head-truncated to fit; the cut marker appears somewhere.
- assert '...' in text
-
- @pytest.mark.asyncio
- async def test_event_count_cap_stops_pagination(self, service):
- """Pagination stops at _ACP_RESUME_MAX_EVENTS even if more pages exist."""
- from openhands.agent_server.models import EventPage
- from openhands.app_server.app_conversation.live_status_app_conversation_service import (
- _ACP_RESUME_MAX_EVENTS,
- )
-
- # Each page has 100 events; cap is 200 so we should stop after 2 pages.
- page_of_100 = EventPage(
- items=[self._make_message_event('user', 'msg') for _ in range(100)],
- next_page_id='more',
- )
- service.event_service.search_events = AsyncMock(return_value=page_of_100)
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- assert (
- service.event_service.search_events.call_count
- == _ACP_RESUME_MAX_EVENTS // 100
- )
-
- @pytest.mark.asyncio
- async def test_tool_dedup_shows_only_terminal_state(self, service):
- """Multiple events for the same tool_call_id render only the terminal one.
-
- ACP streams pending β†’ pending β†’ completed for a single tool call.
- Only the completed entry (with raw_input + raw_output) should appear.
- """
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- tc_id = 'tc-write-42'
- placeholder = ACPToolCallEvent(
- source='agent',
- tool_call_id=tc_id,
- title='Write',
- status='pending',
- raw_input={},
- )
- pending_with_input = ACPToolCallEvent(
- source='agent',
- tool_call_id=tc_id,
- title='Write hello.py',
- status='pending',
- raw_input={'file_path': '/tmp/sandbox/hello.py', 'content': 'x\n'},
- )
- completed = ACPToolCallEvent(
- source='agent',
- tool_call_id=tc_id,
- title='Write hello.py',
- status='completed',
- raw_input={'file_path': '/tmp/sandbox/hello.py', 'content': 'x\n'},
- raw_output='File created successfully at: /tmp/sandbox/hello.py',
- )
- # search returns newest-first
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([completed, pending_with_input, placeholder])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- # Only the completed entry should appear β€” once, not three times.
- assert text.count('[TOOL USE: Write') == 1
- assert '(completed)' in text
- assert '(pending)' not in text
-
- @pytest.mark.asyncio
- async def test_placeholder_tool_event_skipped(self, service):
- """Tool events with no raw_input and no raw_output are not rendered.
-
- These are ACP streaming artifacts emitted before Claude knows the params.
- """
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- placeholder = ACPToolCallEvent(
- source='agent',
- tool_call_id='tc-orphan',
- title='Write',
- status='pending',
- raw_input={},
- )
- real_msg = self._make_message_event('user', 'Do something')
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([placeholder, real_msg])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- assert '[TOOL USE:' not in text
- assert '[USER]: Do something' in text
-
- @pytest.mark.asyncio
- async def test_absolute_paths_stripped_from_tool_details(self, service):
- """Absolute sandbox paths in raw_input/raw_output are reduced to basename."""
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- tool = ACPToolCallEvent(
- source='agent',
- tool_call_id='tc-path',
- title='Write hello.py',
- status='completed',
- raw_input={
- 'file_path': '/private/var/folders/tmp/sandbox-abc/hello.py',
- 'content': 'print("hi")\n',
- },
- raw_output='File created successfully at: /private/var/folders/tmp/sandbox-abc/hello.py',
- )
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([tool])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- # Absolute path must not appear
- assert '/private/var/folders' not in text
- assert '/sandbox-abc' not in text
- # Basename must still be present so the agent knows which file
- assert 'hello.py' in text
-
- @pytest.mark.asyncio
- async def test_action_event_finish_message_rendered(self, service):
- """FinishAction message is rendered as [AGENT]: summary after tool events."""
- from openhands.sdk.event import ActionEvent
-
- finish_ev = ActionEvent.model_validate(
- {
- 'source': 'agent',
- 'thought': [],
- 'thinking_blocks': [],
- 'tool_name': 'finish',
- 'tool_call_id': 'fin-1',
- 'tool_call': {
- 'id': 'fin-1',
- 'name': 'finish',
- 'arguments': '{"message": "All done. Created calculator.py and tests pass."}',
- 'origin': 'completion',
- },
- 'llm_response_id': 'resp-1',
- 'action': {
- 'message': 'All done. Created calculator.py and tests pass.',
- 'kind': 'FinishAction',
- },
- }
- )
- msg_ev = self._make_message_event('user', 'Write calculator.py')
- # Newest-first order (DESC): finish event appears before user msg in page
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([finish_ev, msg_ev])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- assert '[AGENT]: All done. Created calculator.py and tests pass.' in text
- # Agent summary should appear after user message in chronological order
- user_pos = text.index('[USER]:')
- agent_pos = text.index('[AGENT]:')
- assert user_pos < agent_pos
-
- @pytest.mark.asyncio
- async def test_edit_diff_tool_shows_only_filename(self, service):
- """Edit tools with old_string/new_string show only file=<name>, not the diff.
-
- The diff is noise for a resumed agent β€” the file on the persistent
- /workspace volume is the source of truth and can be re-read.
- """
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- edit = ACPToolCallEvent(
- source='agent',
- tool_call_id='tc-edit',
- title='Edit auth.py',
- status='completed',
- raw_input={
- 'file_path': 'auth.py',
- 'old_string': 'def old_func():\n pass',
- 'new_string': 'def new_func():\n return 42',
- 'replace_all': False,
- },
- raw_output='The file auth.py has been updated successfully.',
- )
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([edit])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- assert 'auth.py' in text
- # Diff content must not appear β€” too noisy
- assert 'old_string' not in text
- assert 'new_string' not in text
- assert 'old_func' not in text
- assert 'new_func' not in text
-
- @pytest.mark.asyncio
- async def test_terminal_boilerplate_stripped_from_output(self, service):
- """pytest header lines are stripped; test results are kept."""
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- pytest_output = (
- '============================= test session starts ==============================\n'
- 'platform linux -- Python 3.12.0, pytest-8.0.0, pluggy-1.5.0 -- /usr/bin/python\n'
- 'cachedir: .pytest_cache\n'
- 'rootdir: /sandbox-abc123\n'
- 'plugins: asyncio-0.23.0\n'
- 'asyncio: mode=Mode.STRICT\n'
- 'collecting ... collected 3 items\n'
- '\n'
- 'test_foo.py::test_a PASSED [ 33%]\n'
- 'test_foo.py::test_b PASSED [ 66%]\n'
- 'test_foo.py::test_c PASSED [100%]\n'
- '\n'
- '============================== 3 passed in 0.01s ==============================\n'
- )
- tool = ACPToolCallEvent(
- source='agent',
- tool_call_id='tc-term',
- title='pytest',
- status='completed',
- raw_input={'command': 'pytest test_foo.py -v'},
- raw_output=pytest_output,
- )
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([tool])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- # Boilerplate stripped
- assert 'platform linux' not in text
- assert 'cachedir' not in text
- assert 'rootdir' not in text
- assert 'plugins' not in text
- assert 'asyncio:' not in text
- assert 'collecting' not in text
- assert 'test session starts' not in text
- # Results kept
- assert 'test_a PASSED' in text
- assert '3 passed in 0.01s' in text
-
- @pytest.mark.asyncio
- async def test_failed_terminal_output_shows_tail(self, service):
- """For failed command output the tail (failure details) is shown, not the head."""
- from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
-
- # Simulate a long output where failure is at the end
- passing = '\n'.join(f'test_foo.py::test_{i} PASSED' for i in range(20))
- failure = (
- 'test_foo.py::test_fail FAILED\n'
- 'AssertionError: expected 1 got 2\n'
- '1 failed, 20 passed in 0.05s'
- )
- long_output = passing + '\n' + failure
-
- tool = ACPToolCallEvent(
- source='agent',
- tool_call_id='tc-fail',
- title='pytest',
- status='pending', # is_error drives tail logic
- is_error=True,
- raw_input={'command': 'pytest'},
- raw_output=long_output,
- )
- service.event_service.search_events = AsyncMock(
- return_value=self._make_page([tool])
- )
-
- result = await service._synthesize_acp_resume_initial_message(uuid4())
-
- assert result is not None
- text = result.content[0].text
- # Failure details at the end must appear
- assert 'AssertionError' in text
- assert '1 failed, 20 passed' in text