Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions openhands-sdk/openhands/sdk/agent/response_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,15 +296,15 @@ def _emit_message_event(
def _send_corrective_nudge(self, on_event: ConversationCallbackType) -> None:
"""Inject corrective feedback when no tool call and no content.

Prevents the monologue stuck-detector from firing when the model
simply forgot to emit a function call.
The model still receives this as a user-role message, but the event
source marks that it came from the framework rather than the human.
"""
logger.warning(
"LLM response contained no tool call and no content"
" - sending corrective feedback"
)
nudge = MessageEvent(
source="user",
source="environment",
llm_message=Message(
role="user",
content=[
Expand Down
31 changes: 18 additions & 13 deletions openhands-sdk/openhands/sdk/conversation/visualizer/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@
_ACTION_COLOR = "blue"
_MESSAGE_ASSISTANT_COLOR = _ACTION_COLOR

_MESSAGE_SOURCE_TITLES = {
"agent": "Message from Agent",
"user": "Message from User",
"environment": "Message from Environment",
"hook": "Message from Hook",
}
_MESSAGE_SOURCE_COLORS = {
"agent": _MESSAGE_ASSISTANT_COLOR,
"user": _MESSAGE_USER_COLOR,
"environment": _SYSTEM_COLOR,
"hook": _SYSTEM_COLOR,
}

DEFAULT_HIGHLIGHT_REGEX = {
r"^Reasoning:": f"bold {_THOUGHT_COLOR}",
r"^Thought:": f"bold {_THOUGHT_COLOR}",
Expand Down Expand Up @@ -178,24 +191,16 @@ def _get_action_title(event: Event) -> str:


def _get_message_title(event: Event) -> str:
"""Get title for MessageEvent based on role."""
"""Get title for MessageEvent based on event attribution."""
if isinstance(event, MessageEvent) and event.llm_message:
return (
"Message from User"
if event.llm_message.role == "user"
else "Message from Agent"
)
return _MESSAGE_SOURCE_TITLES[event.source]
return "Message"


def _get_message_color(event: Event) -> str:
"""Get color for MessageEvent based on role."""
"""Get color for MessageEvent based on event attribution."""
if isinstance(event, MessageEvent) and event.llm_message:
return (
_MESSAGE_USER_COLOR
if event.llm_message.role == "user"
else _MESSAGE_ASSISTANT_COLOR
)
return _MESSAGE_SOURCE_COLORS[event.source]
return "white"


Expand Down Expand Up @@ -338,7 +343,7 @@ def _create_event_block(self, event: Event) -> Group | None:
self._skip_user_messages
and isinstance(event, MessageEvent)
and event.llm_message
and event.llm_message.role == "user"
and event.source == "user"
):
return None

Expand Down
28 changes: 19 additions & 9 deletions openhands-tools/openhands/tools/delegate/visualizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,11 @@ def _create_event_block(self, event: Event) -> Group | None:
Returns:
A Rich Group with agent-specific title, or None if visualization fails
"""
# For message events, use our specialized handler
# For message events, use our specialized handler while preserving
# the parent visualizer's source-based user-message filtering.
if isinstance(event, MessageEvent):
if self._skip_user_messages and event.source == "user":
return None
return self._create_message_event_block(event)

# For system prompts, actions, and observations, add agent name to the title
Expand Down Expand Up @@ -187,11 +190,14 @@ def _create_message_event_block(self, event: MessageEvent) -> Group | None:
Create a block for a message event with delegation-specific
sender/receiver info.

For user messages:
For human or delegated messages (source="user"):
- If sender is set: "[Sender] Agent Message to [Agent] Agent"
- Otherwise: "User Message to [Agent] Agent"

For agent messages:
For framework messages (source="environment" or source="hook"):
- "Message from [Source] to [Agent] Agent"

For agent messages (source="agent"):
- Derives recipient from event history (last user message sender)
- If recipient found: "[Agent] Agent Message to [Recipient] Agent"
- Otherwise: "Message from [Agent] Agent to User"
Expand All @@ -208,31 +214,35 @@ def _create_message_event_block(self, event: MessageEvent) -> Group | None:

assert event.llm_message is not None

# Determine role color based on message role
if event.llm_message.role == "user":
# Event source represents authorship; LLM role only controls the wire
# protocol and may intentionally differ for framework feedback.
if event.source == "user":
role_color = "gold3"
elif event.llm_message.role == "assistant":
elif event.source == "agent":
role_color = "blue"
else:
role_color = "white"
role_color = _SYSTEM_COLOR

# Build title with sender/recipient information for delegation
agent_name = self._format_agent_name(self._name) if self._name else "Agent"

if event.llm_message.role == "user":
if event.source == "user":
if event.sender:
# Message from another agent (via delegation)
sender_display = self._format_agent_name(event.sender)
title = f"{sender_display} Agent Message to {agent_name} Agent"
else:
# Regular user message
title = f"User Message to {agent_name} Agent"
elif event.source in ("environment", "hook"):
source_display = event.source.title()
title = f"Message from {source_display} to {agent_name} Agent"
else:
# For agent messages, derive recipient from last user message
recipient = None
if self._state:
for evt in reversed(self._state.events):
if isinstance(evt, MessageEvent) and evt.llm_message.role == "user":
if isinstance(evt, MessageEvent) and evt.source == "user":
recipient = evt.sender
break

Expand Down
88 changes: 85 additions & 3 deletions tests/sdk/agent/test_response_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
from openhands.sdk.agent.response_dispatch import LLMResponseType, classify_response
from openhands.sdk.conversation import Conversation, LocalConversation
from openhands.sdk.conversation.state import ConversationExecutionStatus
from openhands.sdk.event import ActionEvent, Event, MessageEvent
from openhands.sdk.conversation.stuck_detector import StuckDetector
from openhands.sdk.event import ActionEvent, Event, MessageEvent, ObservationEvent
from openhands.sdk.llm import (
LLM,
LLMResponse,
Expand All @@ -21,6 +22,16 @@
ThinkingBlock,
)
from openhands.sdk.llm.utils.metrics import MetricsSnapshot, TokenUsage
from openhands.sdk.tool import Action, Observation


class _LoopAction(Action):
command: str


class _LoopObservation(Observation):
command: str
exit_code: int


def _msg(**kwargs) -> Message:
Expand Down Expand Up @@ -186,6 +197,9 @@ def _make_llm_response(message: Message) -> LLMResponse:

def _run_single_step(
llm_response: LLMResponse,
*,
seed_events: list[Event] | None = None,
record_emitted_events_in_state: bool = False,
) -> tuple[list[Event], LocalConversation]:
"""Run one agent step with a canned LLM response."""
from pydantic import PrivateAttr
Expand All @@ -206,16 +220,62 @@ def completion( # type: ignore[override]
agent = Agent(llm=llm, tools=[])
conversation = Conversation(agent=agent)
conversation._ensure_agent_ready()
if seed_events is not None:
for event in seed_events:
conversation.state.append_event(event)

events: list[Event] = []

def on_event(e: Event) -> None:
events.append(e)
if record_emitted_events_in_state:
conversation.state.append_event(e)

agent.step(conversation, on_event=on_event)
return events, conversation


def _user_message(text: str) -> MessageEvent:
return MessageEvent(
source="user",
llm_message=Message(role="user", content=[TextContent(text=text)]),
)


def _repeating_terminal_loop_events(repeat_count: int) -> list[Event]:
loop_events: list[Event] = []
for i in range(repeat_count):
action = ActionEvent(
source="agent",
thought=[TextContent(text="I need to run ls command")],
action=_LoopAction(command="ls"),
tool_name="terminal",
tool_call_id=f"call_{i}",
tool_call=MessageToolCall(
id=f"call_{i}",
name="terminal",
arguments='{"command": "ls"}',
origin="completion",
),
llm_response_id=f"response_{i}",
)
loop_events.append(action)
loop_events.append(
ObservationEvent(
source="environment",
observation=_LoopObservation.from_text(
text="file1.txt\nfile2.txt",
command="ls",
exit_code=0,
),
action_id=action.id,
tool_name="terminal",
tool_call_id=f"call_{i}",
)
)
return loop_events


def test_content_response_sets_finished():
"""_handle_content_response sets execution status to FINISHED."""
msg = Message(role="assistant", content=[TextContent(text="Done!")])
Expand All @@ -236,7 +296,8 @@ def test_empty_response_sends_nudge():
assert convo.state.execution_status != ConversationExecutionStatus.FINISHED
assert len(msg_events) == 2
assert msg_events[0].source == "agent"
assert msg_events[1].source == "user"
assert msg_events[1].source == "environment"
assert msg_events[1].llm_message.role == "user"
nudge_content = msg_events[1].llm_message.content[0]
assert isinstance(nudge_content, TextContent)
assert "function call" in nudge_content.text
Expand All @@ -251,7 +312,28 @@ def test_reasoning_only_sends_nudge():
assert convo.state.execution_status != ConversationExecutionStatus.FINISHED
assert len(msg_events) == 2
assert msg_events[0].source == "agent"
assert msg_events[1].source == "user"
assert msg_events[1].source == "environment"
assert msg_events[1].llm_message.role == "user"


def test_corrective_nudge_does_not_reset_stuck_detection_window():
"""Framework feedback must not count as a new human turn for stuck detection."""
seed_events = [
_user_message("Please keep trying ls"),
*_repeating_terminal_loop_events(repeat_count=4),
]
msg = Message(role="assistant", content=[])
events, convo = _run_single_step(
_make_llm_response(msg),
seed_events=seed_events,
record_emitted_events_in_state=True,
)
msg_events = [e for e in events if isinstance(e, MessageEvent)]

assert len(msg_events) == 2
assert msg_events[1].source == "environment"
assert msg_events[1].llm_message.role == "user"
assert StuckDetector(convo.state).is_stuck() is True


def test_tool_calls_response_executes_actions():
Expand Down
22 changes: 12 additions & 10 deletions tests/sdk/agent/test_tool_call_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,12 +235,13 @@ def test_reasoning_only_response_injects_nudge():
agent_msgs = [
e for e in events if isinstance(e, MessageEvent) and e.source == "agent"
]
user_nudges = [
e for e in events if isinstance(e, MessageEvent) and e.source == "user"
corrective_nudges = [
e for e in events if isinstance(e, MessageEvent) and e.source == "environment"
]
assert len(agent_msgs) == 1
assert len(user_nudges) == 1
nudge_text = user_nudges[0].llm_message.content[0]
assert len(corrective_nudges) == 1
assert corrective_nudges[0].llm_message.role == "user"
nudge_text = corrective_nudges[0].llm_message.content[0]
assert isinstance(nudge_text, TextContent)
assert "function call" in nudge_text.text

Expand All @@ -262,10 +263,10 @@ def test_content_response_does_not_inject_nudge():
)
agent.step(conv, on_event=events.append)

user_nudges = [
e for e in events if isinstance(e, MessageEvent) and e.source == "user"
corrective_nudges = [
e for e in events if isinstance(e, MessageEvent) and e.source == "environment"
]
assert len(user_nudges) == 0
assert len(corrective_nudges) == 0


def test_completely_empty_response_injects_nudge():
Expand All @@ -285,7 +286,8 @@ def test_completely_empty_response_injects_nudge():
)
agent.step(conv, on_event=events.append)

user_nudges = [
e for e in events if isinstance(e, MessageEvent) and e.source == "user"
corrective_nudges = [
e for e in events if isinstance(e, MessageEvent) and e.source == "environment"
]
assert len(user_nudges) == 1
assert len(corrective_nudges) == 1
assert corrective_nudges[0].llm_message.role == "user"
48 changes: 48 additions & 0 deletions tests/sdk/conversation/test_visualizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,54 @@ def test_message_event_visualize_omits_empty_responses_reasoning_label():
assert "Hello, how can you help me?" in text_content


def test_environment_user_role_message_is_not_titled_as_human_user():
"""Framework user-role messages should not render as human-authored input."""
from rich.console import Console

visualizer = DefaultConversationVisualizer()
event = MessageEvent(
source="environment",
llm_message=Message(
role="user",
content=[TextContent(text="Framework corrective nudge.")],
),
)

block = visualizer._create_event_block(event)
assert block is not None

console = Console()
with console.capture() as capture:
console.print(block)
output = capture.get()

assert "Message from User" not in output
assert "Message from Environment" in output
assert "Framework corrective nudge." in output


def test_skip_user_messages_keeps_environment_user_role_messages():
"""skip_user_messages should skip only real human messages."""
visualizer = DefaultConversationVisualizer(skip_user_messages=True)
human_event = MessageEvent(
source="user",
llm_message=Message(
role="user",
content=[TextContent(text="Human input")],
),
)
environment_event = MessageEvent(
source="environment",
llm_message=Message(
role="user",
content=[TextContent(text="Framework corrective nudge.")],
),
)

assert visualizer._create_event_block(human_event) is None
assert visualizer._create_event_block(environment_event) is not None


def test_agent_error_event_visualize():
"""Test AgentErrorEvent visualization."""
event = AgentErrorEvent(
Expand Down
Loading
Loading