Skip to content

agent-server: message arriving during a finished run's wait_for_pending tail is never processed (stranded until next send) #3363

Closed

Description

@VascoSch92

Summary

In openhands-agent-server, a user message delivered over the events WebSocket while the previous run is still in its post-finish cleanup tail (EventService._run_and_publish awaiting wait_for_pending) is appended to the conversation but never triggers an agent run. It stays unprocessed until the next message arrives.

The agent already handles messages that arrive during a step; this is specifically the window after the run loop has exited but before _run_task is cleared.

User-visible symptom

Send a message → get no response; send another message → it works (and the first one gets answered too). Easy to hit right after an action that immediately precedes a send — e.g. switching the conversation's LLM profile, then sending a message.

Root cause

Incoming WebSocket messages run the agent via sockets.py:

await event_service.send_message(message, True)

EventService.send_message appends the message, then best-effort runs:

async def send_message(self, message: Message, run: bool = False):
    ...
    await loop.run_in_executor(None, self._conversation.send_message, message)
    if run:
        with suppress(ValueError):   # "conversation_already_running" swallowed
            await self.run()

run() refuses if a run task is still around:

if self._run_task is not None and not self._run_task.done():
    raise ValueError("conversation_already_running")

The problem is the lifetime of _run_task. In _run_and_publish, after conversation.run()/arun() returns — i.e. the agent has already finished and the run loop has exited — the task still lingers while it flushes events:

finally:
    if self._callback_wrapper:
        await loop.run_in_executor(
            None, self._callback_wrapper.wait_for_pending, 30.0
        )
    self._run_task = None
    await self._publish_state_update()

So during the wait_for_pending window:

  1. A new user message arrives → conversation.send_message resets the terminal FINISHED/STUCK status to IDLE and appends the event.
  2. send_message(run=True) calls run() → rejected (_run_task not done) → suppressed.
  3. conversation.run() has already returned, so the just-finished run will not pick up the message.
  4. wait_for_pending completes, _run_task = None. Nothing re-runs. The message is stranded at IDLE until the next send.

This is distinct from the in-flight case, which is handled on purpose in LocalConversation.run():

# Note: We intentionally do NOT check for FINISHED status here.
# This allows concurrent user messages to be processed:
# ... Run loop continues to next iteration and processes the message

That mechanism only covers messages arriving while a step is running. The wait_for_pending tail is outside the loop and unguarded.

Why it shows up more in hosted/proxied setups: the tail lasts as long as wait_for_pending takes to flush events to subscribers, so a slow WebSocket client widens the window (cf. the existing _WedgedSubscriber test for that class of problem).

Reproduction (deterministic)

Added to tests/agent_server/test_event_service.py — fails on current code, passes with the fix below:

@pytest.mark.timeout(30)
async def test_message_in_run_cleanup_tail_is_not_stranded(
    real_conversation_service, tmp_path, monkeypatch
):
    """A message that lands while a *finished* run is still in its
    ``wait_for_pending()`` cleanup tail must still be processed."""
    (tmp_path / "ws").mkdir()
    # One scripted reply per user message; each is plain text (no tool calls)
    # so the agent finishes the turn immediately. ``_call_count`` tells us how
    # many turns actually ran.
    parent_llm = SlowTestLLM.from_messages(
        [text_message("reply one"), text_message("reply two")],
        latency_s=0.0,
    )
    info = await start_conversation_with_test_llm(
        real_conversation_service,
        parent_llm=parent_llm,
        workspace_dir=str(tmp_path / "ws"),
        usage_id="tail-strand",
        initial_text=None,
    )
    es = await real_conversation_service.get_event_service(info.id)
    assert es is not None and es._callback_wrapper is not None

    # Park every run in its wait_for_pending() tail until released. It runs in
    # a thread-pool worker, so block on a threading.Event there and signal
    # entry back to the test.
    entered_tail = threading.Event()
    release_tail = threading.Event()

    def _blocking_wait(timeout: float) -> None:
        entered_tail.set()
        release_tail.wait(timeout)

    monkeypatch.setattr(es._callback_wrapper, "wait_for_pending", _blocking_wait)

    # Turn 1: the agent answers "first", finishes (FINISHED), then the run
    # task parks in our blocking wait_for_pending().
    await es.send_message(
        Message(role="user", content=[TextContent(text="first")]), run=True
    )
    assert await asyncio.to_thread(entered_tail.wait, 10.0), (
        "first run never reached its wait_for_pending tail"
    )
    first_run_task = es._run_task
    assert first_run_task is not None
    assert parent_llm._call_count == 1
    assert await es._get_execution_status() == ConversationExecutionStatus.FINISHED

    # Turn 2 arrives DURING the tail: send_message appends it and resets the
    # terminal status to IDLE, then run() is rejected (task not done) and
    # suppressed. Nothing runs yet.
    await es.send_message(
        Message(role="user", content=[TextContent(text="second")]), run=True
    )
    assert parent_llm._call_count == 1, "second turn ran before the tail cleared?!"
    assert es._run_task is first_run_task, "a second run started concurrently"

    # Release the tail; the first run task finishes and clears _run_task.
    release_tail.set()
    await first_run_task

    # The second message must now get processed. On today's agent-server it is
    # stranded (call_count stays 1, status stuck IDLE).
    deadline = time.monotonic() + 5.0
    while parent_llm._call_count < 2 and time.monotonic() < deadline:
        await asyncio.sleep(0.05)

    assert parent_llm._call_count == 2, (
        "second message was stranded — the agent never ran for it after the "
        f"first run's cleanup tail cleared (call_count={parent_llm._call_count}, "
        f"status={await es._get_execution_status()})"
    )

On current code this fails with:

second message was stranded — the agent never ran for it after the first run's
cleanup tail cleared (call_count=1, status=ConversationExecutionStatus.IDLE)
assert 1 == 2

Proposed fix

Re-arm a run at the end of _run_and_publish when the conversation is left IDLE (which only happens when send_message reset a terminal status during the tail — i.e. there is pending input with no run scheduled):

                    # Clear task reference and publish state update
                    self._run_task = None
                    await self._publish_state_update()

                    # Re-arm a run for input that landed while this one was
                    # wrapping up. LocalConversation.run() deliberately keeps
                    # looping on FINISHED so a message arriving *mid-run* is
                    # absorbed; but once the loop has fully exited there is a
                    # gap — this task's wait_for_pending() tail above — in which
                    # an incoming send_message(run=True) has its run() rejected
                    # as "conversation_already_running" and suppressed (see
                    # send_message). send_message() resets the terminal
                    # FINISHED/STUCK status to IDLE, so an IDLE status here means
                    # exactly that: unprocessed input with no run scheduled.
                    # Kick one off so the message isn't stranded until the user
                    # sends again.
                    if (
                        await self._get_execution_status()
                        == ConversationExecutionStatus.IDLE
                    ):
                        with suppress(ValueError):
                            await self.run()

Why this is correct and safe

  • Precise signal. A normal run ends FINISHED; it's only IDLE here if send_message reset FINISHED/STUCK during the tail. So the re-arm fires exactly when there's stranded input, and is a no-op otherwise (zero overhead on the common path).
  • No double-run. _run_task is already None and run() re-checks under _run_lock, so a concurrent message's own run() and the re-arm can't both start a run.
  • Terminates. The re-armed run ends FINISHED → next check is false. It only chains while real input keeps landing in each tail.
  • Respects intent. PAUSED / WAITING_FOR_CONFIRMATION / ERROR are not reset to IDLE by send_message, so they're never auto-re-armed.

Verification

  • New test fails before the change, passes after.
  • Full tests/agent_server/test_event_service.py (78 tests) passes with the change.

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions