Skip to content

🙌 OpenHands: AI-Driven Development

feat: CLI enhancements to support /init, /help and /exit (#7801)

Panduka Muditha7c2f1b075ea1
diff --git a/openhands/core/cli.py b/openhands/core/cli.py
index aa76ab7bca..9d64b00107 100644
--- a/openhands/core/cli.py
+++ b/openhands/core/cli.py
@@ -1,13 +1,27 @@
import asyncio
import logging
import sys
+import time
+from pathlib import Path
+from typing import List, Optional
from uuid import uuid4
+import toml
from prompt_toolkit import PromptSession, print_formatted_text
-from prompt_toolkit.formatted_text import FormattedText
+from prompt_toolkit.application import Application
+from prompt_toolkit.completion import Completer, Completion
+from prompt_toolkit.formatted_text import HTML, FormattedText
from prompt_toolkit.key_binding import KeyBindings
+from prompt_toolkit.layout.containers import HSplit, Window
+from prompt_toolkit.layout.controls import FormattedTextControl
+from prompt_toolkit.layout.layout import Layout
+from prompt_toolkit.patch_stdout import patch_stdout
+from prompt_toolkit.shortcuts import clear, print_container
+from prompt_toolkit.styles import Style
+from prompt_toolkit.widgets import Frame, TextArea
import openhands.agenthub # noqa F401 (we import this to get the agents registered)
+from openhands import __version__
from openhands.core.config import (
AppConfig,
parse_arguments,
@@ -37,89 +51,176 @@ from openhands.events.observation import (
AgentStateChangedObservation,
CmdOutputObservation,
FileEditObservation,
+ FileReadObservation,
)
from openhands.io import read_task
+from openhands.llm.metrics import Metrics
from openhands.mcp import fetch_mcp_tools_from_config
+from openhands.microagent.microagent import BaseMicroagent
+
+# Color and styling constants
+COLOR_GOLD = '#FFD700'
+COLOR_GREY = '#808080'
+DEFAULT_STYLE = Style.from_dict(
+ {
+ 'gold': COLOR_GOLD,
+ 'grey': COLOR_GREY,
+ 'prompt': f'{COLOR_GOLD} bold',
+ }
+)
-prompt_session = PromptSession()
-
-
-def display_message(message: str) -> None:
- print_formatted_text(
- FormattedText(
- [
- ('ansiyellow', '🤖 '),
- ('ansiyellow', message),
- ('', '\n'),
- ]
- )
+COMMANDS = {
+ '/exit': 'Exit the application',
+ '/help': 'Display available commands',
+ '/init': 'Initialize a new repository',
+}
+
+REPO_MD_CREATE_PROMPT = """
+Please explore this repository. Create the file .openhands/microagents/repo.md with:
+- A description of the project
+- An overview of the file structure
+- Any information on how to run tests or other relevant commands
+- Any other information that would be helpful to a brand new developer
+Keep it short--just a few paragraphs will do.
+"""
+
+
+class CommandCompleter(Completer):
+ """Custom completer for commands."""
+
+ def get_completions(self, document, complete_event):
+ text = document.text
+
+ # Only show completions if the user has typed '/'
+ if text.startswith('/'):
+ # If just '/' is typed, show all commands
+ if text == '/':
+ for command, description in COMMANDS.items():
+ yield Completion(
+ command[1:], # Remove the leading '/' as it's already typed
+ start_position=0,
+ display=f'{command} - {description}',
+ )
+ # Otherwise show matching commands
+ else:
+ for command, description in COMMANDS.items():
+ if command.startswith(text):
+ yield Completion(
+ command[len(text) :], # Complete the remaining part
+ start_position=0,
+ display=f'{command} - {description}',
+ )
+
+
+class UsageMetrics:
+ def __init__(self):
+ self.total_cost: float = 0.00
+ self.total_input_tokens: int = 0
+ self.total_output_tokens: int = 0
+ self.total_cache_read: int = 0
+ self.total_cache_write: int = 0
+
+
+prompt_session = PromptSession(style=DEFAULT_STYLE, completer=CommandCompleter())
+
+
+def display_message(message: str):
+ message = message.strip()
+
+ if message:
+ print_formatted_text(f'\n{message}\n')
+
+
+def display_command(command: str):
+ container = Frame(
+ TextArea(
+ text=command,
+ read_only=True,
+ style=COLOR_GREY,
+ wrap_lines=True,
+ ),
+ title='Command Run',
+ style=f'fg:{COLOR_GREY}',
)
+ print_container(container)
+ print_formatted_text('')
-def display_command(command: str) -> None:
+def display_confirmation(confirmation_state: ActionConfirmationStatus):
+ status_map = {
+ ActionConfirmationStatus.CONFIRMED: ('ansigreen', '✅'),
+ ActionConfirmationStatus.REJECTED: ('ansired', '❌'),
+ ActionConfirmationStatus.AWAITING_CONFIRMATION: ('ansiyellow', '⏳'),
+ }
+ color, icon = status_map.get(confirmation_state, ('ansiyellow', ''))
+
print_formatted_text(
FormattedText(
[
- ('', '❯ '),
- ('ansigreen', command),
+ (color, f'{icon} '),
+ (color, str(confirmation_state)),
('', '\n'),
]
)
)
-def display_confirmation(confirmation_state: ActionConfirmationStatus) -> None:
- if confirmation_state == ActionConfirmationStatus.CONFIRMED:
- print_formatted_text(
- FormattedText(
- [
- ('ansigreen', '✅ '),
- ('ansigreen', str(confirmation_state)),
- ('', '\n'),
- ]
- )
- )
- elif confirmation_state == ActionConfirmationStatus.REJECTED:
- print_formatted_text(
- FormattedText(
- [
- ('ansired', '❌ '),
- ('ansired', str(confirmation_state)),
- ('', '\n'),
- ]
- )
- )
- else:
- print_formatted_text(
- FormattedText(
- [
- ('ansiyellow', '⏳ '),
- ('ansiyellow', str(confirmation_state)),
- ('', '\n'),
- ]
- )
- )
-
-
-def display_command_output(output: str) -> None:
+def display_command_output(output: str):
lines = output.split('\n')
+ formatted_lines = []
for line in lines:
if line.startswith('[Python Interpreter') or line.startswith('openhands@'):
# TODO: clean this up once we clean up terminal output
continue
- print_formatted_text(FormattedText([('ansiblue', line)]))
+ formatted_lines.append(line)
+ formatted_lines.append('\n')
+
+ # Remove the last newline if it exists
+ if formatted_lines:
+ formatted_lines.pop()
+
+ container = Frame(
+ TextArea(
+ text=''.join(formatted_lines),
+ read_only=True,
+ style=COLOR_GREY,
+ wrap_lines=True,
+ ),
+ title='Command Output',
+ style=f'fg:{COLOR_GREY}',
+ )
+ print_container(container)
print_formatted_text('')
-def display_file_edit(event: FileEditAction | FileEditObservation) -> None:
- print_formatted_text(
- FormattedText(
- [
- ('ansigreen', str(event)),
- ('', '\n'),
- ]
- )
+def display_file_edit(event: FileEditAction | FileEditObservation):
+ container = Frame(
+ TextArea(
+ text=f'{event}',
+ read_only=True,
+ style=COLOR_GREY,
+ wrap_lines=True,
+ ),
+ title='File Edit',
+ style=f'fg:{COLOR_GREY}',
)
+ print_container(container)
+ print_formatted_text('')
+
+
+def display_file_read(event: FileReadObservation):
+ container = Frame(
+ TextArea(
+ text=f'{event}',
+ read_only=True,
+ style=COLOR_GREY,
+ wrap_lines=True,
+ ),
+ title='File Read',
+ style=f'fg:{COLOR_GREY}',
+ )
+ print_container(container)
+ print_formatted_text('')
def display_event(event: Event, config: AppConfig) -> None:
@@ -137,10 +238,115 @@ def display_event(event: Event, config: AppConfig) -> None:
display_file_edit(event)
if isinstance(event, FileEditObservation):
display_file_edit(event)
+ if isinstance(event, FileReadObservation):
+ display_file_read(event)
if hasattr(event, 'confirmation_state') and config.security.confirmation_mode:
display_confirmation(event.confirmation_state)
+def display_help(style=DEFAULT_STYLE):
+ print_formatted_text(
+ HTML(f'\n<grey>OpenHands CLI v{__version__}</grey>\n'), style=style
+ )
+
+ print_formatted_text(
+ HTML(
+ '<gold>OpenHands CLI lets you interact with the OpenHands agent from the command line.</gold>'
+ )
+ )
+ print_formatted_text('')
+
+ print_formatted_text('Things that you can try:')
+ print_formatted_text(
+ HTML('• Ask questions about the codebase <grey>> How does main.py work?</grey>')
+ )
+ print_formatted_text(
+ HTML(
+ '• Edit files or add new features <grey>> Add a new function to ...</grey>'
+ )
+ )
+ print_formatted_text(
+ HTML('• Find and fix issues <grey>> Fix the type error in ...</grey>')
+ )
+ print_formatted_text('')
+
+ print_formatted_text('Some tips to get the most out of OpenHands:')
+ print_formatted_text(
+ '• Be as specific as possible about the desired outcome or the problem to be solved.'
+ )
+ print_formatted_text(
+ '• Provide context, including relevant file paths and line numbers if available.'
+ )
+ print_formatted_text('• Break large tasks into smaller, manageable prompts.')
+ print_formatted_text('• Include relevant error messages or logs.')
+ print_formatted_text(
+ '• Specify the programming language or framework, if not obvious.'
+ )
+ print_formatted_text('')
+
+ print_formatted_text(HTML('Interactive commands:'), style=style)
+ for command, description in COMMANDS.items():
+ print_formatted_text(
+ HTML(f'<gold><b>{command}</b></gold> - <grey>{description}</grey>'),
+ style=style,
+ )
+ print_formatted_text('')
+ print_formatted_text(
+ HTML(
+ '<grey>Learn more at: https://docs.all-hands.dev/modules/usage/getting-started</grey>'
+ )
+ )
+ print_formatted_text('')
+
+
+def display_banner(session_id: str, is_loaded: asyncio.Event):
+ print_formatted_text(
+ HTML(r"""<gold>
+ ___ _ _ _
+ / _ \ _ __ ___ _ __ | | | | __ _ _ __ __| |___
+ | | | | '_ \ / _ \ '_ \| |_| |/ _` | '_ \ / _` / __|
+ | |_| | |_) | __/ | | | _ | (_| | | | | (_| \__ \
+ \___ /| .__/ \___|_| |_|_| |_|\__,_|_| |_|\__,_|___/
+ |_|
+ </gold>"""),
+ style=DEFAULT_STYLE,
+ )
+
+ print_formatted_text(HTML(f'<grey>OpenHands CLI v{__version__}</grey>'))
+
+ banner_text = (
+ 'Initialized session' if is_loaded.is_set() else 'Initializing session'
+ )
+ print_formatted_text(HTML(f'\n<grey>{banner_text} {session_id}</grey>\n'))
+
+
+def display_welcome_message():
+ print_formatted_text(
+ HTML("<gold>Let's start building!</gold>\n"), style=DEFAULT_STYLE
+ )
+ print_formatted_text(
+ HTML('What do you want to build? <grey>Type /help for help</grey>\n'),
+ style=DEFAULT_STYLE,
+ )
+
+
+def display_initialization_animation(text, is_loaded: asyncio.Event):
+ ANIMATION_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
+
+ i = 0
+ while not is_loaded.is_set():
+ sys.stdout.write('\n')
+ sys.stdout.write(
+ f'\033[s\033[J\033[38;2;255;215;0m[{ANIMATION_FRAMES[i % len(ANIMATION_FRAMES)]}] {text}\033[0m\033[u\033[1A'
+ )
+ sys.stdout.flush()
+ time.sleep(0.1)
+ i += 1
+
+ sys.stdout.write('\r' + ' ' * (len(text) + 10) + '\r')
+ sys.stdout.flush()
+
+
async def read_prompt_input(multiline=False):
try:
if multiline:
@@ -150,35 +356,292 @@ async def read_prompt_input(multiline=False):
def _(event):
event.current_buffer.validate_and_handle()
- message = await prompt_session.prompt_async(
- 'Enter your message and press Ctrl+D to finish:\n',
- multiline=True,
- key_bindings=kb,
- )
+ with patch_stdout():
+ message = await prompt_session.prompt_async(
+ 'Enter your message and press Ctrl+D to finish:\n',
+ multiline=True,
+ key_bindings=kb,
+ )
else:
- message = await prompt_session.prompt_async(
- '>> ',
- )
+ with patch_stdout():
+ message = await prompt_session.prompt_async(
+ '> ',
+ )
return message
except KeyboardInterrupt:
- return 'exit'
+ return '/exit'
except EOFError:
- return 'exit'
+ return '/exit'
async def read_confirmation_input():
try:
confirmation = await prompt_session.prompt_async(
- 'Confirm action (possible security risk)? (y/n) >> ',
+ 'Confirm action (possible security risk)? (y/n) > ',
)
return confirmation.lower() == 'y'
except (KeyboardInterrupt, EOFError):
return False
-async def main(loop: asyncio.AbstractEventLoop) -> None:
+async def init_repository(current_dir: str) -> bool:
+ repo_file_path = Path(current_dir) / '.openhands' / 'microagents' / 'repo.md'
+ init_repo = False
+
+ if repo_file_path.exists():
+ try:
+ content = await asyncio.get_event_loop().run_in_executor(
+ None, read_file, repo_file_path
+ )
+
+ print_formatted_text(
+ 'Repository instructions file (repo.md) already exists.\n'
+ )
+
+ container = Frame(
+ TextArea(
+ text=content,
+ read_only=True,
+ style=COLOR_GREY,
+ wrap_lines=True,
+ ),
+ title='Repository Instructions (repo.md)',
+ style=f'fg:{COLOR_GREY}',
+ )
+ print_container(container)
+ print_formatted_text('') # Add a newline after the frame
+
+ init_repo = cli_confirm(
+ 'Do you want to re-initialize?',
+ ['Yes, re-initialize', 'No, dismiss'],
+ )
+
+ if init_repo:
+ write_to_file(repo_file_path, '')
+ except Exception:
+ print_formatted_text('Error reading repository instructions file (repo.md)')
+ init_repo = False
+ else:
+ print_formatted_text(
+ '\nRepository instructions file will be created by exploring the repository.\n'
+ )
+
+ init_repo = cli_confirm(
+ 'Do you want to proceed?',
+ ['Yes, create', 'No, dismiss'],
+ )
+
+ return init_repo
+
+
+def read_file(file_path):
+ with open(file_path, 'r') as f:
+ return f.read()
+
+
+def write_to_file(file_path, content):
+ with open(file_path, 'w') as f:
+ f.write(content)
+
+
+def cli_confirm(question: str = 'Are you sure?', choices: Optional[List[str]] = None):
+ if choices is None:
+ choices = ['Yes', 'No']
+ selected = [0] # Using list to allow modification in closure
+
+ def get_choice_text():
+ return [
+ ('class:question', f'{question}\n\n'),
+ ] + [
+ (
+ 'class:selected' if i == selected[0] else 'class:unselected',
+ f"{'> ' if i == selected[0] else ' '}{choice}\n",
+ )
+ for i, choice in enumerate(choices)
+ ]
+
+ kb = KeyBindings()
+
+ @kb.add('up')
+ def _(event):
+ selected[0] = (selected[0] - 1) % len(choices)
+
+ @kb.add('down')
+ def _(event):
+ selected[0] = (selected[0] + 1) % len(choices)
+
+ @kb.add('enter')
+ def _(event):
+ event.app.exit(result=selected[0] == 0)
+
+ style = Style.from_dict({'selected': COLOR_GOLD, 'unselected': ''})
+
+ layout = Layout(
+ HSplit(
+ [
+ Window(
+ FormattedTextControl(get_choice_text),
+ always_hide_cursor=True,
+ )
+ ]
+ )
+ )
+
+ app = Application(
+ layout=layout,
+ key_bindings=kb,
+ style=style,
+ mouse_support=True,
+ full_screen=False,
+ )
+
+ return app.run(in_thread=True)
+
+
+def update_usage_metrics(event: Event, usage_metrics: UsageMetrics):
+ """Updates the UsageMetrics object with data from an event's llm_metrics."""
+ if hasattr(event, 'llm_metrics'):
+ llm_metrics: Metrics | None = getattr(event, 'llm_metrics', None)
+ if llm_metrics:
+ # Safely get accumulated_cost
+ cost = getattr(llm_metrics, 'accumulated_cost', 0)
+ # Ensure cost is a number before adding
+ usage_metrics.total_cost += cost if isinstance(cost, float) else 0
+
+ # Safely get token usage details object/dict
+ token_usage = getattr(llm_metrics, 'accumulated_token_usage', None)
+ if token_usage:
+ # Assume object access using getattr, providing defaults
+ prompt_tokens = getattr(token_usage, 'prompt_tokens', 0)
+ completion_tokens = getattr(token_usage, 'completion_tokens', 0)
+ cache_read = getattr(token_usage, 'cache_read_tokens', 0)
+ cache_write = getattr(token_usage, 'cache_write_tokens', 0)
+
+ # Ensure tokens are numbers before adding
+ usage_metrics.total_input_tokens += (
+ prompt_tokens if isinstance(prompt_tokens, int) else 0
+ )
+ usage_metrics.total_output_tokens += (
+ completion_tokens if isinstance(completion_tokens, int) else 0
+ )
+ usage_metrics.total_cache_read += (
+ cache_read if isinstance(cache_read, int) else 0
+ )
+ usage_metrics.total_cache_write += (
+ cache_write if isinstance(cache_write, int) else 0
+ )
+
+
+def shutdown(usage_metrics: UsageMetrics, session_id: str):
+ cost_str = f'${usage_metrics.total_cost:.6f}'
+ input_tokens_str = f'{usage_metrics.total_input_tokens:,}'
+ cache_read_str = f'{usage_metrics.total_cache_read:,}'
+ cache_write_str = f'{usage_metrics.total_cache_write:,}'
+ output_tokens_str = f'{usage_metrics.total_output_tokens:,}'
+ total_tokens_str = (
+ f'{usage_metrics.total_input_tokens + usage_metrics.total_output_tokens:,}'
+ )
+
+ labels_and_values = [
+ (' Total Cost (USD):', cost_str),
+ (' Total Input Tokens:', input_tokens_str),
+ (' Cache Hits:', cache_read_str),
+ (' Cache Writes:', cache_write_str),
+ (' Total Output Tokens:', output_tokens_str),
+ (' Total Tokens:', total_tokens_str),
+ ]
+
+ # Calculate max widths for alignment
+ max_label_width = max(len(label) for label, _ in labels_and_values)
+ max_value_width = max(len(value) for _, value in labels_and_values)
+
+ # Construct the summary text with aligned columns
+ summary_lines = [
+ f'{label:<{max_label_width}} {value:>{max_value_width}}'
+ for label, value in labels_and_values
+ ]
+ summary_text = '\n'.join(summary_lines)
+
+ container = Frame(
+ TextArea(
+ text=summary_text,
+ read_only=True,
+ style=COLOR_GREY,
+ wrap_lines=True,
+ ),
+ title='Session Summary',
+ style=f'fg:{COLOR_GREY}',
+ )
+ print_container(container)
+ print_formatted_text(HTML(f'\n<grey>Closed session {session_id}</grey>\n'))
+
+
+def manage_openhands_file(folder_path=None, add_to_trusted=False):
+ openhands_file = Path.home() / '.openhands.toml'
+ default_content: dict = {'trusted_dirs': []}
+
+ if not openhands_file.exists():
+ with open(openhands_file, 'w') as f:
+ toml.dump(default_content, f)
+
+ if folder_path:
+ with open(openhands_file, 'r') as f:
+ try:
+ config = toml.load(f)
+ except Exception:
+ config = default_content
+
+ if 'trusted_dirs' not in config:
+ config['trusted_dirs'] = []
+
+ if folder_path in config['trusted_dirs']:
+ return True
+
+ if add_to_trusted:
+ config['trusted_dirs'].append(folder_path)
+ with open(openhands_file, 'w') as f:
+ toml.dump(config, f)
+
+ return False
+
+ return False
+
+
+def check_folder_security_agreement(current_dir):
+ is_trusted = manage_openhands_file(current_dir)
+
+ if not is_trusted:
+ security_frame = Frame(
+ TextArea(
+ text=(
+ f'Do you trust the files in this folder?\n\n'
+ f'{current_dir}\n\n'
+ 'OpenHands may read and execute files in this folder with your permission.'
+ ),
+ style='#ffffff',
+ read_only=True,
+ wrap_lines=True,
+ )
+ )
+
+ clear()
+ print_container(security_frame)
+
+ confirm = cli_confirm('Do you wish to continue?', ['Yes, proceed', 'No, exit'])
+
+ if confirm:
+ manage_openhands_file(current_dir, add_to_trusted=True)
+
+ return confirm
+
+ return True
+
+
+async def main(loop: asyncio.AbstractEventLoop):
"""Runs the agent in CLI mode."""
+ reload_microagents = False
+
args = parse_arguments()
logger.setLevel(logging.WARNING)
@@ -186,6 +649,12 @@ async def main(loop: asyncio.AbstractEventLoop) -> None:
# Load config from toml and override with command line arguments
config: AppConfig = setup_config_from_args(args)
+ # TODO: Set working directory from config or use current working directory?
+ current_dir = config.workspace_base
+
+ if not current_dir:
+ raise ValueError('Workspace base directory not specified')
+
# Read task from file, CLI args, or stdin
task_str = read_task(args, config.cli_multiline_input)
@@ -193,7 +662,15 @@ async def main(loop: asyncio.AbstractEventLoop) -> None:
initial_user_action = MessageAction(content=task_str) if task_str else None
sid = str(uuid4())
- display_message(f'Session ID: {sid}')
+ is_loaded = asyncio.Event()
+
+ # Show OpenHands banner and session ID
+ display_banner(session_id=sid, is_loaded=is_loaded)
+
+ # Show Initialization loader
+ loop.run_in_executor(
+ None, display_initialization_animation, 'Initializing...', is_loaded
+ )
agent = create_agent(config)
mcp_tools = await fetch_mcp_tools_from_config(config.mcp)
@@ -209,26 +686,64 @@ async def main(loop: asyncio.AbstractEventLoop) -> None:
event_stream = runtime.event_stream
- async def prompt_for_next_task() -> None:
- next_message = await read_prompt_input(config.cli_multiline_input)
- if not next_message.strip():
- await prompt_for_next_task()
- if next_message == 'exit':
- event_stream.add_event(
- ChangeAgentStateAction(AgentState.STOPPED), EventSource.ENVIRONMENT
- )
+ usage_metrics = UsageMetrics()
+
+ async def prompt_for_next_task():
+ nonlocal reload_microagents
+ while True:
+ next_message = await read_prompt_input(config.cli_multiline_input)
+
+ if not next_message.strip():
+ continue
+
+ if next_message == '/exit':
+ event_stream.add_event(
+ ChangeAgentStateAction(AgentState.STOPPED), EventSource.ENVIRONMENT
+ )
+ shutdown(usage_metrics, sid)
+ return
+ elif next_message == '/help':
+ display_help()
+ continue
+ elif next_message == '/init':
+ if config.runtime == 'local':
+ init_repo = await init_repository(current_dir)
+ if init_repo:
+ event_stream.add_event(
+ MessageAction(content=REPO_MD_CREATE_PROMPT),
+ EventSource.USER,
+ )
+ reload_microagents = True
+ return
+ else:
+ print_formatted_text(
+ '\nRepository initialization through the CLI is only supported for local runtime.\n'
+ )
+ continue
+
+ action = MessageAction(content=next_message)
+ event_stream.add_event(action, EventSource.USER)
return
- action = MessageAction(content=next_message)
- event_stream.add_event(action, EventSource.USER)
async def on_event_async(event: Event) -> None:
+ nonlocal reload_microagents
display_event(event, config)
+ update_usage_metrics(event, usage_metrics)
+
if isinstance(event, AgentStateChangedObservation):
if event.agent_state in [
AgentState.AWAITING_USER_INPUT,
AgentState.FINISHED,
]:
+ # Reload microagents after initialization of repo.md
+ if reload_microagents:
+ microagents: list[BaseMicroagent] = (
+ runtime.get_microagents_from_selected_repo(None)
+ )
+ memory.load_user_workspace_microagents(microagents)
+ reload_microagents = False
await prompt_for_next_task()
+
if event.agent_state == AgentState.AWAITING_USER_CONFIRMATION:
user_confirmed = await read_confirmation_input()
if user_confirmed:
@@ -266,6 +781,25 @@ async def main(loop: asyncio.AbstractEventLoop) -> None:
repo_directory=repo_directory,
)
+ # Clear loading animation
+ is_loaded.set()
+
+ if not check_folder_security_agreement(current_dir):
+ # User rejected, exit application
+ event_stream.add_event(
+ ChangeAgentStateAction(AgentState.STOPPED), EventSource.ENVIRONMENT
+ )
+ return
+
+ # Clear the terminal
+ clear()
+
+ # Show OpenHands banner and session ID
+ display_banner(session_id=sid, is_loaded=is_loaded)
+
+ # Show OpenHands welcome
+ display_welcome_message()
+
if initial_user_action:
# If there's an initial user action, enqueue it and do not prompt again
event_stream.add_event(initial_user_action, EventSource.USER)
diff --git a/tests/unit/test_cli_basic.py b/tests/unit/test_cli_basic_prompts.py
similarity index 76%
rename from tests/unit/test_cli_basic.py
rename to tests/unit/test_cli_basic_prompts.py
index 0251bbf647..96895d5060 100644
--- a/tests/unit/test_cli_basic.py
+++ b/tests/unit/test_cli_basic_prompts.py
@@ -10,10 +10,8 @@ from prompt_toolkit.output import create_output
from openhands.core.cli import main
from openhands.core.config import AppConfig
-from openhands.core.schema import AgentState
from openhands.events.action import MessageAction
from openhands.events.event import EventSource
-from openhands.events.observation import AgentStateChangedObservation
class MockEventStream:
@@ -88,6 +86,7 @@ def mock_config():
mock_config.security.confirmation_mode = False
mock_config.sandbox = Mock()
mock_config.sandbox.selected_repo = None
+ mock_config.workspace_base = '/test'
mock_setup_config.return_value = mock_config
yield mock_config
@@ -126,44 +125,32 @@ def mock_runtime():
@pytest.mark.asyncio
-async def test_cli_greeting(
+async def test_cli_basic_prompt(
mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
):
buffer = StringIO()
- with create_app_session(
- input=create_pipe_input(), output=create_output(stdout=buffer)
- ):
- mock_controller.status_callback = None
+ with patch('openhands.core.cli.manage_openhands_file', return_value=True):
+ with patch('openhands.core.cli.cli_confirm', return_value=True):
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
- main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
- await asyncio.sleep(0.1)
+ await asyncio.sleep(0.1)
- hello_response = MessageAction(content='Ping')
- hello_response._source = EventSource.AGENT
- mock_runtime.event_stream.add_event(hello_response, EventSource.AGENT)
+ hello_response = MessageAction(content='Ping')
+ hello_response._source = EventSource.AGENT
+ mock_runtime.event_stream.add_event(hello_response, EventSource.AGENT)
- state_change = AgentStateChangedObservation(
- content='Awaiting user input', agent_state=AgentState.AWAITING_USER_INPUT
- )
- state_change._source = EventSource.AGENT
- mock_runtime.event_stream.add_event(state_change, EventSource.AGENT)
+ try:
+ await asyncio.wait_for(main_task, timeout=1.0)
+ except asyncio.TimeoutError:
+ main_task.cancel()
- stop_event = AgentStateChangedObservation(
- content='Stop', agent_state=AgentState.STOPPED
- )
- stop_event._source = EventSource.AGENT
- mock_runtime.event_stream.add_event(stop_event, EventSource.AGENT)
+ buffer.seek(0)
+ output = buffer.read()
- mock_controller.state.agent_state = AgentState.STOPPED
-
- try:
- await asyncio.wait_for(main_task, timeout=1.0)
- except asyncio.TimeoutError:
- main_task.cancel()
-
- buffer.seek(0)
- output = buffer.read()
-
- assert 'Ping' in output
+ assert 'Ping' in output
diff --git a/tests/unit/test_cli_commands.py b/tests/unit/test_cli_commands.py
new file mode 100644
index 0000000000..0542a46d8b
--- /dev/null
+++ b/tests/unit/test_cli_commands.py
@@ -0,0 +1,368 @@
+import asyncio
+from io import StringIO
+from unittest.mock import AsyncMock, Mock, patch
+
+import pytest
+from prompt_toolkit.application import create_app_session
+from prompt_toolkit.input import create_pipe_input
+from prompt_toolkit.output import create_output
+
+from openhands.core.cli import main
+from openhands.core.config import AppConfig
+from openhands.core.schema import AgentState
+from openhands.events.action import ChangeAgentStateAction, MessageAction
+from openhands.events.event import EventSource
+from openhands.events.observation import AgentStateChangedObservation
+
+
+class MockEventStream:
+ def __init__(self):
+ self._subscribers = {}
+ self.cur_id = 0
+ self.events = []
+
+ def subscribe(self, subscriber_id, callback, callback_id=None):
+ if subscriber_id not in self._subscribers:
+ self._subscribers[subscriber_id] = {}
+ self._subscribers[subscriber_id][callback_id] = callback
+ return callback_id
+
+ def unsubscribe(self, subscriber_id, callback_id):
+ if (
+ subscriber_id in self._subscribers
+ and callback_id in self._subscribers[subscriber_id]
+ ):
+ del self._subscribers[subscriber_id][callback_id]
+
+ def add_event(self, event, source):
+ event._id = self.cur_id
+ self.cur_id += 1
+ event._source = source
+ event._timestamp = '2023-01-01T00:00:00'
+ self.events.append((event, source))
+
+ for subscriber_id in self._subscribers:
+ for callback_id, callback in self._subscribers[subscriber_id].items():
+ if asyncio.iscoroutinefunction(callback):
+ asyncio.create_task(callback(event))
+ else:
+ callback(event)
+
+
+def mock_agent():
+ with patch('openhands.core.cli.create_agent') as mock_create_agent:
+ mock_agent_instance = AsyncMock()
+ mock_agent_instance.name = 'test-agent'
+ mock_agent_instance.llm = AsyncMock()
+ mock_agent_instance.llm.config = AsyncMock()
+ mock_agent_instance.llm.config.model = 'test-model'
+ mock_agent_instance.llm.config.base_url = 'http://test'
+ mock_agent_instance.llm.config.max_message_chars = 1000
+ mock_agent_instance.config = AsyncMock()
+ mock_agent_instance.config.disabled_microagents = []
+ mock_agent_instance.sandbox_plugins = []
+ mock_agent_instance.prompt_manager = AsyncMock()
+ mock_create_agent.return_value = mock_agent_instance
+ yield mock_agent_instance
+
+
+def mock_controller():
+ with patch('openhands.core.cli.create_controller') as mock_create_controller:
+ mock_controller_instance = AsyncMock()
+ mock_controller_instance.state.agent_state = None
+ # Mock run_until_done to finish immediately
+ mock_controller_instance.run_until_done = AsyncMock(return_value=None)
+ mock_create_controller.return_value = (mock_controller_instance, None)
+ yield mock_controller_instance
+
+
+def mock_config():
+ with patch('openhands.core.cli.parse_arguments') as mock_parse_args:
+ args = Mock()
+ args.file = None
+ args.task = None
+ args.directory = None
+ mock_parse_args.return_value = args
+ with patch('openhands.core.cli.setup_config_from_args') as mock_setup_config:
+ mock_config = AppConfig()
+ mock_config.cli_multiline_input = False
+ mock_config.security = Mock()
+ mock_config.security.confirmation_mode = False
+ mock_config.sandbox = Mock()
+ mock_config.sandbox.selected_repo = None
+ mock_config.workspace_base = '/test'
+ mock_config.runtime = 'local' # Important for /init test
+ mock_setup_config.return_value = mock_config
+ yield mock_config
+
+
+def mock_memory():
+ with patch('openhands.core.cli.create_memory') as mock_create_memory:
+ mock_memory_instance = AsyncMock()
+ mock_create_memory.return_value = mock_memory_instance
+ yield mock_memory_instance
+
+
+def mock_read_task():
+ with patch('openhands.core.cli.read_task') as mock_read_task:
+ mock_read_task.return_value = None
+ yield mock_read_task
+
+
+def mock_runtime():
+ with patch('openhands.core.cli.create_runtime') as mock_create_runtime:
+ mock_runtime_instance = AsyncMock()
+
+ mock_event_stream = MockEventStream()
+ mock_runtime_instance.event_stream = mock_event_stream
+
+ mock_runtime_instance.connect = AsyncMock()
+
+ # Ensure status_callback is None
+ mock_runtime_instance.status_callback = None
+ # Mock get_microagents_from_selected_repo
+ mock_runtime_instance.get_microagents_from_selected_repo = Mock(return_value=[])
+ mock_create_runtime.return_value = mock_runtime_instance
+ yield mock_runtime_instance
+
+
+async def test_help_command(
+ mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
+):
+ buffer = StringIO()
+
+ with patch('openhands.core.cli.manage_openhands_file', return_value=True):
+ with patch(
+ 'openhands.core.cli.check_folder_security_agreement', return_value=True
+ ):
+ with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
+ # Setup to return /help first, then simulate an exit
+ mock_prompt.side_effect = ['/help', '/exit']
+
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
+
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+
+ agent_ready_event = AgentStateChangedObservation(
+ agent_state=AgentState.AWAITING_USER_INPUT,
+ content='Agent is ready for user input',
+ )
+ mock_runtime.event_stream.add_event(
+ agent_ready_event, EventSource.AGENT
+ )
+
+ await asyncio.sleep(0.1)
+
+ try:
+ await asyncio.wait_for(main_task, timeout=0.5)
+ except asyncio.TimeoutError:
+ main_task.cancel()
+ try:
+ await main_task
+ except asyncio.CancelledError:
+ pass
+
+ buffer.seek(0)
+ output = buffer.read()
+
+ # Verify help output was displayed
+ assert 'OpenHands CLI' in output
+ assert 'Things that you can try' in output
+ assert 'Interactive commands' in output
+ assert '/help' in output
+ assert '/exit' in output
+
+ # Verify the help command didn't add a MessageAction to the event stream
+ message_actions = [
+ event
+ for event, _ in mock_runtime.event_stream.events
+ if isinstance(event, MessageAction)
+ ]
+ assert len(message_actions) == 0
+
+
+async def test_exit_command(
+ mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
+):
+ buffer = StringIO()
+
+ with patch('openhands.core.cli.manage_openhands_file', return_value=True):
+ with patch(
+ 'openhands.core.cli.check_folder_security_agreement', return_value=True
+ ):
+ with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
+ # First prompt call returns /exit
+ mock_prompt.side_effect = ['/exit']
+
+ with patch('openhands.core.cli.shutdown') as mock_shutdown:
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
+
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+
+ agent_ready_event = AgentStateChangedObservation(
+ agent_state=AgentState.AWAITING_USER_INPUT,
+ content='Agent is ready for user input',
+ )
+ mock_runtime.event_stream.add_event(
+ agent_ready_event, EventSource.AGENT
+ )
+
+ await asyncio.sleep(0.1)
+
+ try:
+ await asyncio.wait_for(main_task, timeout=0.5)
+ except asyncio.TimeoutError:
+ main_task.cancel()
+ try:
+ await main_task
+ except asyncio.CancelledError:
+ pass
+
+ # Verify that the exit command sent a STOPPED state change event
+ state_change_events = [
+ event
+ for event, source in mock_runtime.event_stream.events
+ if isinstance(event, ChangeAgentStateAction)
+ and event.agent_state == AgentState.STOPPED
+ and source == EventSource.ENVIRONMENT
+ ]
+ assert len(state_change_events) == 1
+
+ # Verify shutdown was called
+ mock_shutdown.assert_called_once()
+
+
+async def test_init_command(
+ mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
+):
+ buffer = StringIO()
+
+ with patch('openhands.core.cli.manage_openhands_file', return_value=True):
+ with patch(
+ 'openhands.core.cli.check_folder_security_agreement', return_value=True
+ ):
+ with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
+ # First prompt call returns /init, second call returns /exit
+ mock_prompt.side_effect = ['/init', '/exit']
+
+ with patch('openhands.core.cli.init_repository') as mock_init_repo:
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
+
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+
+ agent_ready_event = AgentStateChangedObservation(
+ agent_state=AgentState.AWAITING_USER_INPUT,
+ content='Agent is ready for user input',
+ )
+ mock_runtime.event_stream.add_event(
+ agent_ready_event, EventSource.AGENT
+ )
+
+ await asyncio.sleep(0.1)
+
+ try:
+ await asyncio.wait_for(main_task, timeout=0.5)
+ except asyncio.TimeoutError:
+ main_task.cancel()
+ try:
+ await main_task
+ except asyncio.CancelledError:
+ pass
+
+ # Verify init_repository was called with the correct directory
+ mock_init_repo.assert_called_once_with('/test')
+
+ # Verify that a MessageAction was sent with the repository creation prompt
+ message_events = [
+ event
+ for event, source in mock_runtime.event_stream.events
+ if isinstance(event, MessageAction)
+ and 'Please explore this repository' in event.content
+ and source == EventSource.USER
+ ]
+ assert len(message_events) == 1
+
+
+async def test_init_command_non_local_runtime(
+ mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
+):
+ buffer = StringIO()
+
+ # Set runtime to non-local for this test
+ mock_config.runtime = 'remote'
+
+ with patch('openhands.core.cli.manage_openhands_file', return_value=True):
+ with patch(
+ 'openhands.core.cli.check_folder_security_agreement', return_value=True
+ ):
+ with patch('openhands.core.cli.read_prompt_input') as mock_prompt:
+ # First prompt call returns /init, second call returns /exit
+ mock_prompt.side_effect = ['/init', '/exit']
+
+ with patch('openhands.core.cli.init_repository') as mock_init_repo:
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
+
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+
+ # Send AgentStateChangedObservation to trigger prompt
+ agent_ready_event = AgentStateChangedObservation(
+ agent_state=AgentState.AWAITING_USER_INPUT,
+ content='Agent is ready for user input',
+ )
+ mock_runtime.event_stream.add_event(
+ agent_ready_event, EventSource.AGENT
+ )
+
+ await asyncio.sleep(0.1)
+
+ try:
+ await asyncio.wait_for(main_task, timeout=0.5)
+ except asyncio.TimeoutError:
+ main_task.cancel()
+ try:
+ await main_task
+ except asyncio.CancelledError:
+ pass
+
+ buffer.seek(0)
+ output = buffer.read()
+
+ # Verify error message was displayed
+ assert (
+ 'Repository initialization through the CLI is only supported for local runtime'
+ in output
+ )
+
+ # Verify init_repository was not called
+ mock_init_repo.assert_not_called()
+
+ # Verify no MessageAction was sent for repository creation
+ message_events = [
+ event
+ for event, _ in mock_runtime.event_stream.events
+ if isinstance(event, MessageAction)
+ and 'Please explore this repository' in event.content
+ ]
+ assert len(message_events) == 0
diff --git a/tests/unit/test_cli_sid.py b/tests/unit/test_cli_sid.py
deleted file mode 100644
index c24f9e6233..0000000000
--- a/tests/unit/test_cli_sid.py
+++ /dev/null
@@ -1,127 +0,0 @@
-import asyncio
-from argparse import Namespace
-from io import StringIO
-from pathlib import Path
-from unittest.mock import AsyncMock, Mock, patch
-
-import pytest
-from prompt_toolkit.application import create_app_session
-from prompt_toolkit.input import create_pipe_input
-from prompt_toolkit.output import create_output
-
-from openhands.core.cli import main
-from openhands.core.config import AppConfig
-from openhands.core.schema import AgentState
-from openhands.events.event import EventSource
-from openhands.events.observation import AgentStateChangedObservation
-
-
-def mock_runtime():
- with patch('openhands.core.cli.create_runtime') as mock_create_runtime:
- mock_runtime_instance = AsyncMock()
- # Mock the event stream with proper async methods
- mock_event_stream = AsyncMock()
- mock_event_stream.subscribe = AsyncMock()
- mock_event_stream.add_event = AsyncMock()
- mock_event_stream.get_events = AsyncMock(return_value=[])
- mock_event_stream.get_latest_event_id = AsyncMock(return_value=0)
- mock_runtime_instance.event_stream = mock_event_stream
- # Mock connect method to return immediately
- mock_runtime_instance.connect = AsyncMock()
- # Ensure status_callback is None
- mock_runtime_instance.status_callback = None
- # Mock get_microagents_from_selected_repo
- mock_runtime_instance.get_microagents_from_selected_repo = Mock(return_value=[])
- mock_create_runtime.return_value = mock_runtime_instance
- yield mock_runtime_instance
-
-
-def mock_agent():
- with patch('openhands.core.cli.create_agent') as mock_create_agent:
- mock_agent_instance = AsyncMock()
- mock_agent_instance.name = 'test-agent'
- mock_agent_instance.llm = AsyncMock()
- mock_agent_instance.llm.config = AsyncMock()
- mock_agent_instance.llm.config.model = 'test-model'
- mock_agent_instance.llm.config.base_url = 'http://test'
- mock_agent_instance.llm.config.max_message_chars = 1000
- mock_agent_instance.config = AsyncMock()
- mock_agent_instance.config.disabled_microagents = []
- mock_agent_instance.sandbox_plugins = []
- mock_agent_instance.prompt_manager = AsyncMock()
- mock_create_agent.return_value = mock_agent_instance
- yield mock_agent_instance
-
-
-def mock_controller():
- with patch('openhands.core.cli.create_controller') as mock_create_controller:
- mock_controller_instance = AsyncMock()
- # Mock run_until_done to finish immediately
- mock_controller_instance.run_until_done = AsyncMock(return_value=None)
- mock_create_controller.return_value = (mock_controller_instance, None)
- yield mock_controller_instance
-
-
-def task_file(tmp_path: Path) -> Path:
- # Create a temporary file with our task
- task_file = tmp_path / 'task.txt'
- task_file.write_text('Ask me what your task is')
- return task_file
-
-
-def mock_config(task_file: Path):
- with patch('openhands.core.cli.parse_arguments') as mock_parse_args:
- # Create a proper Namespace with our temporary task file
- args = Namespace(file=str(task_file), task=None, directory=None)
- mock_parse_args.return_value = args
- with patch('openhands.core.cli.setup_config_from_args') as mock_setup_config:
- mock_config = AppConfig()
- mock_setup_config.return_value = mock_config
- yield mock_config
-
-
-async def test_cli_session_id_output(
- mock_runtime, mock_agent, mock_controller, mock_config
-):
- # status_callback is set when initializing the runtime
- mock_controller.status_callback = None
-
- buffer = StringIO()
-
- # Use input patch just for the exit command
- with patch('builtins.input', return_value='exit'):
- with create_app_session(
- input=create_pipe_input(), output=create_output(stdout=buffer)
- ):
- # Create a task for main
- main_task = asyncio.create_task(main(asyncio.get_event_loop()))
-
- # Give it a moment to display the session ID
- await asyncio.sleep(0.1)
-
- # Trigger agent state change to STOPPED to end the main loop
- event = AgentStateChangedObservation(
- content='Stop', agent_state=AgentState.STOPPED
- )
- event._source = EventSource.AGENT
- await mock_runtime.event_stream.add_event(event)
-
- # Wait for main to finish with a timeout
- try:
- await asyncio.wait_for(main_task, timeout=1.0)
- except asyncio.TimeoutError:
- main_task.cancel()
-
- buffer.seek(0)
- output = buffer.read()
-
- # Check the output
- assert 'Session ID:' in output
- # Also verify that our task message was processed
- assert 'Ask me what your task is' in str(mock_runtime.mock_calls)
diff --git a/tests/unit/test_cli_startup.py b/tests/unit/test_cli_startup.py
new file mode 100644
index 0000000000..4b713e870d
--- /dev/null
+++ b/tests/unit/test_cli_startup.py
@@ -0,0 +1,301 @@
+import asyncio
+from datetime import datetime
+from io import StringIO
+from unittest.mock import AsyncMock, Mock, patch
+
+import pytest
+from prompt_toolkit.application import create_app_session
+from prompt_toolkit.input import create_pipe_input
+from prompt_toolkit.output import create_output
+
+from openhands.core.cli import main
+from openhands.core.config import AppConfig
+
+
+class MockEventStream:
+ def __init__(self):
+ self._subscribers = {}
+ self.cur_id = 0
+
+ def subscribe(self, subscriber_id, callback, callback_id):
+ if subscriber_id not in self._subscribers:
+ self._subscribers[subscriber_id] = {}
+ self._subscribers[subscriber_id][callback_id] = callback
+
+ def unsubscribe(self, subscriber_id, callback_id):
+ if (
+ subscriber_id in self._subscribers
+ and callback_id in self._subscribers[subscriber_id]
+ ):
+ del self._subscribers[subscriber_id][callback_id]
+
+ def add_event(self, event, source):
+ event._id = self.cur_id
+ self.cur_id += 1
+ event._source = source
+ event._timestamp = datetime.now().isoformat()
+
+ for subscriber_id in self._subscribers:
+ for callback_id, callback in self._subscribers[subscriber_id].items():
+ callback(event)
+
+
+def mock_agent():
+ with patch('openhands.core.cli.create_agent') as mock_create_agent:
+ mock_agent_instance = AsyncMock()
+ mock_agent_instance.name = 'test-agent'
+ mock_agent_instance.llm = AsyncMock()
+ mock_agent_instance.llm.config = AsyncMock()
+ mock_agent_instance.llm.config.model = 'test-model'
+ mock_agent_instance.llm.config.base_url = 'http://test'
+ mock_agent_instance.llm.config.max_message_chars = 1000
+ mock_agent_instance.config = AsyncMock()
+ mock_agent_instance.config.disabled_microagents = []
+ mock_agent_instance.sandbox_plugins = []
+ mock_agent_instance.prompt_manager = AsyncMock()
+ mock_create_agent.return_value = mock_agent_instance
+ yield mock_agent_instance
+
+
+def mock_controller():
+ with patch('openhands.core.cli.create_controller') as mock_create_controller:
+ mock_controller_instance = AsyncMock()
+ mock_controller_instance.state.agent_state = None
+ # Mock run_until_done to finish immediately
+ mock_controller_instance.run_until_done = AsyncMock(return_value=None)
+ mock_create_controller.return_value = (mock_controller_instance, None)
+ yield mock_controller_instance
+
+
+def mock_config():
+ with patch('openhands.core.cli.parse_arguments') as mock_parse_args:
+ args = Mock()
+ args.file = None
+ args.task = None
+ args.directory = None
+ mock_parse_args.return_value = args
+ with patch('openhands.core.cli.setup_config_from_args') as mock_setup_config:
+ mock_config = AppConfig()
+ mock_config.cli_multiline_input = False
+ mock_config.security = Mock()
+ mock_config.security.confirmation_mode = False
+ mock_config.sandbox = Mock()
+ mock_config.sandbox.selected_repo = None
+ mock_config.workspace_base = '/test'
+ mock_setup_config.return_value = mock_config
+ yield mock_config
+
+
+def mock_memory():
+ with patch('openhands.core.cli.create_memory') as mock_create_memory:
+ mock_memory_instance = AsyncMock()
+ mock_create_memory.return_value = mock_memory_instance
+ yield mock_memory_instance
+
+
+def mock_read_task():
+ with patch('openhands.core.cli.read_task') as mock_read_task:
+ mock_read_task.return_value = None
+ yield mock_read_task
+
+
+def mock_runtime():
+ with patch('openhands.core.cli.create_runtime') as mock_create_runtime:
+ mock_runtime_instance = AsyncMock()
+
+ mock_event_stream = MockEventStream()
+ mock_runtime_instance.event_stream = mock_event_stream
+
+ mock_runtime_instance.connect = AsyncMock()
+
+ # Ensure status_callback is None
+ mock_runtime_instance.status_callback = None
+ # Mock get_microagents_from_selected_repo
+ mock_runtime_instance.get_microagents_from_selected_repo = Mock(return_value=[])
+ mock_create_runtime.return_value = mock_runtime_instance
+ yield mock_runtime_instance
+
+
+async def test_cli_startup_folder_security_confirmation_agree(
+ mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
+):
+ buffer = StringIO()
+
+ with patch(
+ 'openhands.core.cli.manage_openhands_file', return_value=False
+ ) as mock_manage_openhands_file:
+ with patch(
+ 'openhands.core.cli.cli_confirm', return_value=True
+ ) as mock_cli_confirm:
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
+
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+
+ await asyncio.sleep(0.1)
+
+ try:
+ await asyncio.wait_for(main_task, timeout=0.1)
+ except Exception:
+ main_task.cancel()
+
+ buffer.seek(0)
+ output = buffer.read()
+
+ # ASCII art banner
+ assert '___' in output
+
+ # Version information
+ assert 'OpenHands CLI v' in output
+
+ # Session initialization
+ assert 'Initializing session' in output
+
+ # Folder security confirmation
+ assert 'Do you trust the files in this folder?' in output
+ assert '/test' in output
+ assert (
+ 'OpenHands may read and execute files in this folder with your permission.'
+ in output
+ )
+
+ # Confirmation prompt
+ mock_manage_openhands_file.assert_any_call('/test')
+ mock_cli_confirm.assert_called_once_with(
+ 'Do you wish to continue?', ['Yes, proceed', 'No, exit']
+ )
+ mock_manage_openhands_file.assert_any_call('/test', add_to_trusted=True)
+
+ # Session initialization complete
+ assert 'Initialized session' in output
+
+ # Welcome message
+ assert "Let's start building!" in output
+ assert 'What do you want to build?' in output
+ assert 'Type /help for help' in output
+
+
+async def test_cli_startup_folder_security_confirmation_disagree(
+ mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
+):
+ buffer = StringIO()
+
+ with patch(
+ 'openhands.core.cli.manage_openhands_file', return_value=False
+ ) as mock_manage_openhands_file:
+ with patch(
+ 'openhands.core.cli.cli_confirm', return_value=False
+ ) as mock_cli_confirm:
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
+
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+
+ await asyncio.sleep(0.1)
+
+ try:
+ await asyncio.wait_for(main_task, timeout=0.1)
+ except Exception:
+ main_task.cancel()
+
+ buffer.seek(0)
+ output = buffer.read()
+
+ # ASCII art banner
+ assert '___' in output
+
+ # Version information
+ assert 'OpenHands CLI v' in output
+
+ # Session initialization
+ assert 'Initializing session' in output
+
+ # Folder security confirmation
+ assert 'Do you trust the files in this folder?' in output
+ assert '/test' in output
+ assert (
+ 'OpenHands may read and execute files in this folder with your permission.'
+ in output
+ )
+
+ # Confirmation prompt
+ mock_manage_openhands_file.assert_called_once_with('/test')
+ mock_cli_confirm.assert_called_once_with(
+ 'Do you wish to continue?', ['Yes, proceed', 'No, exit']
+ )
+
+ # Session initialization complete
+ assert 'Initialized session' not in output
+
+ # Welcome message
+ assert "Let's start building!" not in output
+ assert 'What do you want to build?' not in output
+ assert 'Type /help for help' not in output
+
+
+async def test_cli_startup_trusted_folder(
+ mock_runtime, mock_controller, mock_config, mock_agent, mock_memory, mock_read_task
+):
+ buffer = StringIO()
+
+ with patch('openhands.core.cli.manage_openhands_file', return_value=True):
+ with patch(
+ 'openhands.core.cli.cli_confirm', return_value=True
+ ) as mock_cli_confirm:
+ with create_app_session(
+ input=create_pipe_input(), output=create_output(stdout=buffer)
+ ):
+ mock_controller.status_callback = None
+
+ main_task = asyncio.create_task(main(asyncio.get_event_loop()))
+
+ await asyncio.sleep(0.1)
+
+ try:
+ await asyncio.wait_for(main_task, timeout=0.1)
+ except Exception:
+ main_task.cancel()
+
+ buffer.seek(0)
+ output = buffer.read()
+
+ # ASCII art banner
+ assert '___' in output
+
+ # Version information
+ assert 'OpenHands CLI v' in output
+
+ # Session initialization
+ assert 'Initializing session' in output
+
+ # Folder security confirmation should not be shown
+ assert 'Do you trust the files in this folder?' not in output
+ assert '/test' not in output
+ assert (
+ 'OpenHands may read and execute files in this folder with your permission.'
+ not in output
+ )
+
+ # Confirmation prompt should not be shown
+ mock_cli_confirm.assert_not_called()
+
+ # Session initialization
+ assert 'Initialized session' in output
+
+ # Welcome message
+ assert "Let's start building!" in output
+ assert 'What do you want to build?' in output
+ assert 'Type /help for help' in output